提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
用一句话总结了归并排序:先把左半边数组排好序,再把右半边数组排好序,然后把两半数组合并。 同时我提了一个问题,让你一句话总结快速排序,这里说一下我的答案: 快速排序是先将一个元素排好序,然后再将剩下的元素排好序。
class Solution {
public int[] sortArray(int[] nums) {
Quick.sort(nums);
return nums;
}
}
class Quick{
public static void sort(int[] nums){
shuffle(nums);
quickSort(nums,0,nums.length-1);
}
public static void quickSort(int[] nums, int low, int high){
if(low >= high){
return;
}
int index = part(nums, low, high);
quickSort(nums,low, index-1);
quickSort(nums,index+1,high);
}
public static int part(int[] nums, int low, int high){
int flag = nums[low];
while(low < high){
while(low<high && nums[high] >= flag)high--;
nums[low] = nums[high];
while(low<high && nums[low] <= flag)low++;
nums[high] = nums[low];
}
nums[low] = flag;
return low;
}
public static void shuffle(int[] nums){
Random rand = new Random();
for(int i = 0; i < nums.length; i ++){
int r = i + rand.nextInt(nums.length-i);
swap(nums,i,r);
}
}
public static void swap(int[] nums,int low, int high){
int temp = nums[low];
nums[low] = nums[high];
nums[high] = temp;
}
}
优先级队列
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int a : nums){
pq.offer(a);
if(pq.size() > k){
pq.poll();
}
}
return pq.peek();
}
}
快排
class Solution {
public int findKthLargest(int[] nums, int k) {
fullss(nums,0,nums.length-1);
quickSort(nums,0, nums.length-1,nums.length-k);
return nums[nums.length-k];
}
public void quickSort(int[] nums ,int low, int high,int k){
if(low >= high){
return;
}
int index = part(nums,low,high);
quickSort(nums,low,index-1,k);
quickSort(nums,index+1,high,k);
}
public int part(int[] nums, int low, int high){
int flag = nums[low];
while(low < high){
while(low<high && nums[high] >= flag)high--;
nums[low] = nums[high];
while(low < high && nums[low] <= flag)low ++;
nums[high] = nums[low];
}
nums[low] = flag;
return low;
}
public void fullss(int[] nums, int low, int high){
Random rand = new Random();
for(int i = 0; i < nums.length; i ++){
int r = i + rand.nextInt(nums.length-i);
int temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
}
}