912. Sort an Array**

​https://leetcode.com/problems/sort-an-array/​

题目描述

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​

C++ 实现 1

三路快排, 快排的关键在于 ​​partition​​ 这一步操作, 找到合适的 index.

class Solution {
private:
int partition(vector<int> &nums, int start, int end) {
if (nums.empty() || start > end) return -1;
int ridx = std::rand() % (end - start + 1) + start;
swap(nums[ridx], nums[start]);
int target = nums[start];
int lt = start, gt = end + 1, i = start + 1;
// nums[start+1...lt] < target, nums[lt+1, ...gt) == target, nums[gt ... end] > target
while (i < gt) {
if (nums[i] == target) ++ i;
else if (nums[i] < target) std::swap(nums[++lt], nums[i++]);
else std::swap(nums[--gt], nums[i]);
}
std::swap(nums[start], nums[lt]);
return lt;
}
void quicksort(vector<int> &nums, int start, int end) {
if (nums.empty() || start >= end) return;
int idx = partition(nums, start, end);
quicksort(nums, start, idx - 1);
quicksort(nums, idx + 1, end);
}
public:
vector<int> sortArray(vector<int>& nums) {
quicksort(nums, 0, nums.size() - 1);
return nums;
}
};