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 ;
}
};