題目地址:
https://leetcode.com/problems/high-five/
給定一個二維數組,每一行代表某個學生的某一科目分數,第一個數字是學生id,第二個數字是分數。要求返回一個數組,存儲每個學生最高的門課的平均分(返回整型即可),並且數組要按學生id排序。
思路是哈希表 + 堆。哈希表key存id,value存一個堆,堆裏存id對應的學生的最高無門課的分數。代碼如下:
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Solution {
public int[][] highFive(int[][] items) {
// 用TreeMap就可以在遍歷的時候按照id從小到大遍歷了
Map<Integer, PriorityQueue<Integer>> map = new TreeMap<>();
for (int[] item : items) {
map.putIfAbsent(item[0], new PriorityQueue<>());
PriorityQueue<Integer> minHeap = map.get(item[0]);
if (minHeap.size() < 5) {
minHeap.offer(item[1]);
} else {
if (item[1] > minHeap.peek()) {
minHeap.poll();
minHeap.offer(item[1]);
}
}
}
int[][] res = new int[map.size()][2];
int idx = 0;
for (Map.Entry<Integer, PriorityQueue<Integer>> entry : map.entrySet()) {
res[idx][0] = entry.getKey();
int sum = 0;
for (int score : entry.getValue()) {
sum += score;
}
res[idx][1] = sum / 5;
idx++;
}
return res;
}
}
時間複雜度,空間,爲數組長度,爲學生數量。