High Five
给一个2d数组, 里面是[id, score], 求每个id的top 5 score的average, 并且还要按照id排序.
因为要排序, 所以先排序, 然后只加top5即可.
class Solution {
public int[][] highFive(int[][] items) {
Arrays.sort(items, (a,b) -> (a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]));
List<int[]> list = new ArrayList<>();
int i = 0;
while(i < items.length){
int cur = items[i][0];
int sum = 0;
for(int j = 0; j < 5; i++,j++){
sum += items[i][1];
}
list.add(new int[]{cur, sum / 5});
while(i < items.length && cur == items[i][0]){
i++;
}
}
int[][] res = new int[list.size()][2];
for(int k = 0; k < list.size(); k++){
res[k][0] = list.get(k)[0];
res[k][1] = list.get(k)[1];
}
return res;
}
}