天天看點

2018搜狐春招後端開發實習題解

第一題:
import java.util.*;
/*搜狐已經累計擁有千萬級别會員使用者,會員成長值公式為:會員成長值=每天成長值+任務成長值。
 *輸入一組數組,第一行是n,表示接下來有n行資料輸入,
 *從第二行開始,如果第一個是1,則該行有4個資料,
 *第一個1表示每日成長規則,第二個數字表示開始時間,第三個數字表示截止時間,第四個數字表示每日成長值。
 *如果第一個數字是2,則該行總共有3個數字,第二個數字表示某一天做任務,第三個數字表示任務成長值。
 *每日總的成長值=每日成長值+任務成長值;若每日成長值有多個,以最大的那個值為準。例如:
  3
  1 1 5 10
  2 3 4
  1 4 6 -5
輸出49
 */
public class SystemDesign {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		int sum = 0;
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for(int i = 0;i < n;i ++) {
			int flag = s.nextInt();	//辨別位,為1表示每天成長值,為2表示任務成長值
			if(flag == 1) {
				int start = s.nextInt();
				int end = s.nextInt();
				int base = s.nextInt();
				for(int j = start;j <= end;j ++) {
					if(map.containsKey(j)) {
						int value = map.get(j);
						if(base > value) {	//若每日成長值有多個,以最大的那個值為準
							map.put(j, base);
						}
					}
					else {
						map.put(j, base);
					}				    			    
				}
			}
			if(flag == 2) {
				int key = s.nextInt();
				int addValue = s.nextInt();	//任務成長值直接疊加
				if(map.containsKey(key)) {
					int value = map.get(key);
					value += addValue;
					map.put(key, value);
				}
				else {
					map.put(key, addValue);
				}
			}
		}
		//求和
		for(int i : map.values()) {
			sum += i;
		}
		System.out.println(sum);
	}
}
第二題:
import java.util.Arrays;
import java.util.Scanner;
/*
n個整數,輸出最小的k個,
第一行輸入n,k第二行輸入n個整數,輸出從小到大k個最小整數,并用逗号隔開。
如:
8 4
4 5 1 6 2 7 3 8
輸出:
1,2,3,4
 */
public class PrintKMinValue {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		while(s.hasNext()) {
			int n = s.nextInt();	//數組長度
			int k = s.nextInt();	//最小的k個數
			int[] nums = new int[n];
			for(int i = 0;i < n;i ++) {
				nums[i] = s.nextInt();
			}
			Arrays.sort(nums);
			for(int i = 0;i < k;i ++) {
				if(i != k - 1) {
					System.out.print(nums[i] + ",");
				}
				else {
					System.out.print(nums[i]);	//最後一個不需要輸出,
				}
			}
		}		
	}
}