LeetCode 1471: The k Strongest Values in an Array
Problem Description
Explanation
To solve this problem, we first find the center value of the array by sorting it and taking the element at position (n-1)/2
. Then, we calculate the strength of each element relative to the center value. The strength is defined as the absolute difference between the element and the center value. If two elements have the same strength, we compare their actual values to determine the stronger one.
After calculating the strength for each element, we sort the array based on strength and value in descending order. Finally, we return the first k elements from the sorted array as the k strongest values.
- Time Complexity: O(nlogn) where n is the length of the input array arr due to sorting.
- Space Complexity: O(n) for storing the strengths and values.
Solutions
import java.util.*;
class Solution {
public int[] getStrongest(int[] arr, int k) {
Arrays.sort(arr);
int n = arr.length;
int center = arr[(n - 1) / 2];
Integer[] strength = new Integer[n];
for (int i = 0; i < n; i++) {
strength[i] = Math.abs(arr[i] - center);
}
Arrays.sort(arr, (a, b) -> {
int diff = strength[b] - strength[a];
if (diff == 0) {
return b - a;
}
return diff;
});
return Arrays.copyOfRange(arr, 0, k);
}
}
Loading editor...