快速排序及其使用
Posted 划小船
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序及其使用相关的知识,希望对你有一定的参考价值。
Sort an Array(快速排序)
912. Sort an Array
Description
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
Solution
class Solution {
public int[] sortArray(int[] nums) {
quickSort(nums, 0, nums.length-1);
return nums;
}
private void quickSort(int[] a, int start, int end){
if(start<end){
int pivot = a[start];
int i = start;
int j = end;
while(i<j){
while(i<j&&pivot<a[j]){
j--;
}
if(i<j){
a[i] = a[j];
a[j] = pivot;
i++;
}
while(i<j&&a[i]<pivot){
i++;
}
if(i<j){
a[j] = a[i];
a[i] = pivot;
j--;
}
}
quickSort(a, start, i-1);
quickSort(a, i+1, end);
}
}
}
数组中的第K个最大元素
215. Kth Largest Element in an Array
Description
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Constraints:
1 <= k <= nums.length <= 104
-104 <= nums[i] <= 104
Solution
class Solution {
public int findKthLargest(int[] nums, int k) {
int n = nums.length, low = 0, high = n-1;
while(low<=high){
int x = partition(nums, low, high);
if(x == n-k){
return nums[x];
}else if(x < n-k){
low = x+1;
}else{
high = x-1;
}
}
return low;
}
private int partition(int[] nums, int low, int high){
int i = low;
int j = high;
int pivot = nums[i];
while(i<j){
while(i<j && pivot<nums[j]){
j--;
}
if(i<j){
nums[i] = nums[j];
nums[j] = pivot;
i++;
}
while(i<j && pivot>nums[i]){
i++;
}
if(i<j){
nums[j] = nums[i];
nums[i] = pivot;
j--;
}
}
return i;
}
}
总结
快速排序是面试中经常出现的一道题目,由于其时间复杂度低,经常被用于各种排序场景。
解决数组中第K个最大元素,可以借助快速排序的思想,每次将第i的元素前面放入比nums[i]小的元素,后面放入比num[i]大的元素,便于在短时间内找到第K的最大元素。
二者都要注意边界条件和最终的return,防止出现死循环现象。
以上是关于快速排序及其使用的主要内容,如果未能解决你的问题,请参考以下文章