1. 找出数组中的第 K 大整数
直接排序要不得,比如:2,21,12,1如使用Arrays.sort排序,会得到:
1,12,2,21的序列,因为字符串按照第一位开始排序
(1)Arrays.sort 改排序规则
class Solution {
public String kthLargestNumber(String[] nums, int k) {
Arrays.sort(nums, new Comparator<String>() {
public int compare(String num1, String num2) {
if (num1.length() != num2.length())
return num1.length() - num2.length();
else
return num1.compareTo(num2);
}
});
return nums[nums.length - k];
}
}
(2)优先队列(改排序规则)
class Solution {
public String kthLargestNumber(String[] nums, int k) {
//大顶堆,优先队列
PriorityQueue<String> queue = new PriorityQueue<>((o1, o2) -> {
if(o1.length() != o2.length()) {
return o2.length() - o1.length();
}
return o2.compareTo(o1);
});
for (String num : nums) {
queue.add(num);
}
while (k > 1) {
queue.poll();
k--;
}
return queue.poll();
}
}
(2)转化为数字后排序
可直接转为数字后再排序,但是如传入字符串数字过大,会报错
class Solution {
public String kthLargestNumber(String[] nums, int k) {
int[] arr = new int[nums.length];
int len = nums.length;
for (int i = 0; i < len; i++) {
arr[i] = Integer.parseInt(nums[i]);
}
Arrays.sort(arr);
return String.valueOf(arr[len - k]);
}
}
(3)快排改善(不可含重复元素)
但是遇到以下,只要数组中有重复元素就会超时:
输入:nums = [“0”,“0”], k = 2
输出:“0”
class Solution {
public String kthLargestNumber(String[] nums, int k) {
int len = nums.length;
int left = 0;
int right = len - 1;
// 转换一下,第 k 大元素的索引是 len - k
int target = len - k;
while (true) {
int index = partition(nums, left, right);
if (index == target) {
return nums[index];
} else if (index < target) {
left = index + 1;
} else {
right = index - 1;
}
}
}
public int partition(String[] arr, int left, int right) {
// 哨兵划分操作, left为哨兵
int i = left, j = right;
while (i < j) {
while (i < j && (arr[j].compareTo(arr[left]) > 0 && arr[j].length() == arr[left].length()) || arr[j].length() > arr[left].length())
j--;
while (i < j && (arr[i].compareTo(arr[left]) < 0 && arr[i].length() == arr[left].length()) || arr[i].length() < arr[left].length())
i++;
swap(arr, i, j);
}
swap(arr, i, left);
// 递归左(右)子数组执行哨兵划分,并且返回确定元素位置
return i;
}
private void swap(String[] arr, int i, int j) {
String tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}