912. 排序数组
为保证权益,题目请参考 912. 排序数组(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// leetcode 912
// 快速排序
class Solution {
public:
vector<int> sortArray(vector<int> &nums) {
// 使用快速排序!
helper(nums, 0, nums.size() - 1);
return nums;
}
void helper(vector<int> &nums, int left, int right) {
if(left >= right){
return;
}
int ori_left = left;
int ori_right = right;
int target = right;
// right = right - 1;
while (left < right) {
while (nums[left] <= nums[target] && left < right) {
left++;
}
while (nums[right] >= nums[target] && left < right) {
right--;
}
if (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
if(left == right && left != target){
int temp = nums[left];
nums[left] = nums[target];
nums[target] = temp;
}
this->helper(nums, ori_left, left - 1);
this->helper(nums, left + 1, ori_right);
}
};
int main() {
vector<int> vec;
// vec.push_back(1);
// vec.push_back(4);
// vec.push_back(3);
vec.push_back(6);
vec.push_back(5);
// vec.push_back(2);
Solution so;
so.sortArray(vec);
for(int x: vec){
cout << x << endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
解决方案2
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// leetcode 912
// 快速排序
class Solution {
public:
vector<int> sortArray(vector<int> &nums) {
// 使用快速排序!
sort(nums.begin(), nums.end());
return nums;
}
};
int main() {
vector<int> vec;
// vec.push_back(1);
// vec.push_back(4);
// vec.push_back(3);
vec.push_back(6);
vec.push_back(5);
// vec.push_back(2);
Solution so;
so.sortArray(vec);
for(int x: vec){
cout << x << endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34