LEETCODE-1471-数组中的k个最强值
题目参考:https://leetcode.cn/problems/the-k-strongest-values-in-an-array/
题解参考:https://leetcode.cn/problems/the-k-strongest-values-in-an-array/solution/8402-7544-by-bobby996/
我的题解
class Solution {
public int[] getStrongest(int[] arr, int k) {
// 数组转集合
List<Integer> list = Arrays.stream(arr).boxed().sorted().collect(Collectors.toList());
/*
* 根据题意求取中位数
* 10 20 30 40 50 60 maxIndex:5, mind:30
* 10 20 30 40 50 60 70 maxIndex:6, mind:40
*/
int maxIndex = list.size() - 1;
int m = list.get(maxIndex / 2);
// 获取前k个最强值
list = list.stream().sorted((o1, o2) ->
Math.abs(o1 - m) == Math.abs(o2 - m)
? -(o1 - o2)
: -(Math.abs(o1 - m) - Math.abs(o2 - m)))
.limit(k).collect(Collectors.toList());
// 集合转数组返回
int[] ints = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
ints[i] = list.get(i);
}
return ints;
}
}
其他题解
class Solution {
public int[] getStrongest(int[] arr, int k) {
Arrays.sort(arr);
int[] ans = new int[k];
int n = arr.length,
l = 0,
r = n - 1,
m = arr[(n - 1) / 2],
idx = 0;
while (idx != k) {
int abs1 = Math.abs(arr[l] - m), abs2 = Math.abs(arr[r] - m);
ans[idx++] = abs1 > abs2
? arr[l++]
: arr[r--];
}
return ans;
}
}
DJOSIMON