请问我这个是快速排序吗?
class Solution {
public:
void fsort(vector<int>& nums, int left, int right)
{
if(left>=right)
return;
int i=left;int j=right;
while(1)
{
while(nums[i]<=nums[right]&&i<j)
i++;
while(nums[j]>=nums[right]&&i<j)
j--;
if(i<j)
{
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
}
else
{
{
int g=nums[i];
nums[i]=nums[right];
nums[right]=g;
}
break;
}
}
fsort(nums,left,i-1);
fsort(nums,i+1,right);
}
vector<int> sortArray(vector<int>& nums) {
fsort(nums,0,nums.size()-1);
return nums;
}
};
为什么和官方的比慢了这么多。我只能通过11/20,后面就超时了,官方17/20
下面是官方的
class Solution {
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[r];
int i = l - 1;
for (int j = l; j <= r - 1; ++j) {
if (nums[j] <= pivot) {
i = i + 1;
swap(nums[i], nums[j]);
}
}
swap(nums[i + 1], nums[r]);
return i + 1;
}
int randomized_partition(vector<int>& nums, int l, int r) {
int i = rand() % (r - l + 1) + l; // 随机选一个作为我们的主元
swap(nums[r], nums[i]);
return partition(nums, l, r);
}
void randomized_quicksort(vector<int>& nums, int l, int r) {
if (l < r) {
int pos = randomized_partition(nums, l, r);
randomized_quicksort(nums, l, pos - 1);
randomized_quicksort(nums, pos + 1, r);
}
}
public:
vector<int> sortArray(vector<int>& nums) {
srand((unsigned)time(NULL));
randomized_quicksort(nums, 0, (int)nums.size() - 1);
return nums;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/sort-an-array/solutions/178305/pai-xu-shu-zu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目是leetcode912.排序数组