网易2019实习生招聘算法题(一)
题目
为了找到自己满意的工作,牛牛收集了每种工作的难度和报酬。
牛牛选工作的标准是在难度不超过自身能力值的情况下,牛牛选择报酬最高的工作。
牛牛的小伙伴太多了,于是他只好把这个任务交给了你。
输入描述:
每个输入包含一个测试用例。
每个测试用例的第一行包含两个正整数,分别表示工作的数量N(N<=100000)和小伙伴的数量M(M<=100000)。
接下来的N行每行包含两个正整数,分别表示该项工作的难度Di(Di<=1000000000)和报酬Pi(Pi<=1000000000)。
接下来的一行包含M个正整数,分别表示M个小伙伴的能力值Ai(Ai<=1000000000)。
保证不存在两项工作的报酬相同。
输出描述:
对于每个小伙伴,在单独的一行输出一个正整数表示他能得到的最高报酬。一个工作可以被多个人选择。
示例
输入
3 3
1 100
10 1000
1000000000 1001
9 10 1000000000
输出
100
1000
1001
解题思路:
方案一:
Step1: 工作难度跟报酬存储在哈希表中,另存工作难度在数组a[0~n]中
Step2 : 把小伙伴初始报酬记为0,与工作能力值一起存在上一个哈希表中;同时a[n~n+m]存小伙伴的能力值.
Step3 : 排序数组a(从小到大)(数组大小为n+m)
Step4(关键) : 循环比较,得到每个当前能力值以下最大的报酬max,同时替换哈希表中的键值对
Step5: 输出.
复杂度分析 :
空间复杂度 : O(n);
时间复杂度 O(n*log n);
code :
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int t1=0, t2=0;
HashMap<Integer, Integer> hs = new HashMap<>();
int[] a = new int[n+m];
int[] b = new int[m];
for (int i=0; i<n; i++) {
t1 = sc.nextInt();
t2 = sc.nextInt();
a[i] = t1;
hs.put(t1, t2);
}
for (int i = 0; i < m; i++) {
t1 = sc.nextInt();
a[n+i] = t1;
b[i] = t1;
if( !hs.containsKey(t1) )
hs.put(t1, 0);
}
Arrays.sort(a);
int max = 0;
for (int i = 0; i < m + n; i++) {
max = Math.max(max, hs.get(a[i]));
hs.put(a[i], max);
}
for (int i = 0; i < m; i++) {
System.out.println(hs.get(b[i]));
}
}
}
方案二
Step1 : 二维数组arr存储工作难度与报酬;
Step2 : arr从小到大按 报酬 排序;
Step3 : 利用TreeMap的floorKey函数获取map中小于等于能力值的Key,输出;
复杂度分析 :
空间复杂度 : O(n);
时间复杂度 O(n*log n);
code :
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int[][] arr = new int[N][2];
TreeMap map = new TreeMap();
for (int i = 0; i < N; i++) {
arr[i][0] = sc.nextInt();
arr[i][1] = sc.nextInt();
}
Arrays.sort(arr, (e1, e2) -> (int)(e1[0] - e2[0]));
for (int i = 1; i < arr.length; i++) {
arr[i][1] = Math.max(arr[i-1][1], arr[i][1]);
}
for (int i = 0; i < arr.length; i++) {
map.put(arr[i][0], arr[i][1]);
}
for (int i = 0; i < M; i++) {
int ability = sc.nextInt();
Integer index = map.floorKey(ability);
if (index != null) {
System.out.println(map.get(index));
} else {
System.out.println(0);
}
}
}
}
结语
- 如觉不妥,欢迎交流谈论~
- @MingLachsis