题目描述
leecode第912题:排序数组:
给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
cpp
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
cpp
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
cpp
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
代码:
cpp
//归并排序优化
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
int len = nums.size();
//优化1:全局使用一份临时数组
int *temp = new int[len];
mergeSort(nums, 0, len - 1, temp);
return nums;
}
void mergeSort(vector<int>& nums, int left, int right, int* temp){
if(right == left){
return;
}
int mid = left + (right - left)/2;
mergeSort(nums, left, mid, temp);
mergeSort(nums, mid + 1, right, temp);
//优化2:在两部分数组已经有序的情况下,不再合并
if(nums[mid] < nums[mid+1]){
return;
}
mergeOfTwoSortedArray(nums, left, mid, right, temp);
}
void mergeOfTwoSortedArray(vector<int>& nums, int left, int mid, int right, int* temp){
for(int i = left; i<=right; i++){
temp[i] = nums[i];
}
int i = left, j = mid + 1;
for(int k = left; k<=right; k++){
if(i == mid+1){
nums[k] = temp[j];
j++;
}
else if(j == right + 1){
nums[k] = temp[i];
i++;
}
else if(temp[i] <= temp[j]){//这一行的else没写曾经耗费了很长时间排查
nums[k] = temp[i];
i++;
}
else if(temp[i] > temp[j]){
nums[k] = temp[j];
j++;
}
}
}
};