912. Sort an Array**

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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章