【leetcode】【medium】【每日一題】912. Sort an Array

912. 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

題目鏈接:https://leetcode-cn.com/problems/sort-an-array/

 

思路

題目很簡單,排序算法的練習,可參考此篇總結:排序算法總結|數組和鏈表實現的對比|c++

這裏選快排進行實現。

class Solution {
public:
    vector<int> sortArray(vector<int>& nums) {
        int len = nums.size();
        if(len<=1) return nums;
        sort(nums, 0, len-1); 
        return nums;
    }
    void sort(vector<int> &nums, int left, int right){
        if(left>=right) return;
        int key = nums[left], l = left, r = right;
        while(l<r){
            while(l<r && nums[r]>key){
                --r;
            }
            if(l<r){
                nums[l++] = nums[r];
            }
            while(l<r && nums[l]<key){
                ++l;
            }
            if(l<r){
                nums[r--] = nums[l];
            }
        }
        nums[l] = key;
        sort(nums, left, l-1);
        sort(nums, l+1, right);
        return ;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章