912. 排序数组(点击跳转LeetCode)
给你一个整数数组nums
,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
题解
语言:C++
思路:归并排序
class Solution {
vector<int> tmp;
void merge_sort(vector<int>& nums , int l , int r){
int mid = l + r >> 1;
if(l >= r){
return;
}
merge_sort(nums , l , mid);
merge_sort(nums , mid + 1 , r);
int k = 0;
int i = l;
int j = mid + 1;
while(i <= mid && j <= r){
if(nums[i] <= nums[j]){
tmp[k++] = nums[i++];
}else{
tmp[k++] = nums[j++];
}
}
while(i <= mid){
tmp[k++] = nums[i++];
}
while(j <= r){
tmp[k++] = nums[j++];
}
for(i = l , j = 0 ; i <= r ; i ++ , j ++){
nums[i] = tmp[j];
}
}
public:
vector<int> sortArray(vector<int>& nums) {
tmp.resize((int)nums.size(), 0);
merge_sort(nums , 0 , nums.size()-1);
return nums;
}
};