Skip to content

Commit 1b1f80c

Browse files
committed
update solution
1 parent 71f45b4 commit 1b1f80c

File tree

3 files changed

+46
-15
lines changed

3 files changed

+46
-15
lines changed

DivideConquer/215_KthLargestElementArray.cpp

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/*
22
* @Author: [email protected]
3-
* @Last Modified time: 2016-08-29 11:18:00
3+
* @Last Modified time: 2016-08-30 09:42:07
44
*/
55

66
class Solution {
@@ -29,28 +29,30 @@ class Solution {
2929
return pivot_index;
3030
}
3131

32-
int findKthLargest(vector<int> &nums, int k) {
33-
int left = 0, right = nums.size();
34-
if(k>right || k<=0) return -1;
32+
int find_kth_number(vector<int> &arr, int k){
33+
int begin = 0, end = arr.size();
34+
assert(k>0 && k<=end);
3535

36-
while(left < right){
37-
int pos = partition(nums, left, right);
36+
int target_num = 0;
37+
while (begin < end){
38+
int pos = partition(arr, begin, end);
3839
if(pos == k-1){
39-
return nums[pos];
40+
target_num = arr[pos];
41+
break;
4042
}
4143
else if(pos > k-1){
42-
right = pos;
44+
end = pos;
4345
}
4446
else{
45-
left = pos + 1;
47+
begin = pos + 1;
4648
}
4749
}
48-
return -1;
50+
return target_num;
4951
}
5052
};
5153

5254

53-
class Solution {
55+
class Solution_2 {
5456
public:
5557
/*
5658
Other possibility is to use a min heap that will store the K-th largest values.

TwoPointers/75_SortColors.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* @Author: [email protected]
3+
* @Last Modified time: 2016-08-30 13:04:54
4+
*/
5+
6+
class Solution {
7+
public:
8+
// Wiki: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
9+
void sortColors(vector<int>& nums) {
10+
int pos_put_red = 0, pos_put_blue = nums.size()-1;
11+
int scan_index = 0;
12+
while(scan_index <= pos_put_blue){
13+
if(nums[scan_index] == 0){
14+
swap(nums[scan_index++], nums[pos_put_red++]);
15+
}
16+
else if(nums[scan_index] == 2){
17+
swap(nums[scan_index], nums[pos_put_blue--]);
18+
}
19+
else{
20+
scan_index ++;
21+
}
22+
}
23+
}
24+
};
25+
26+
/*
27+
[0]
28+
[1,0]
29+
[0,1,2]
30+
[1,1,1,2,0,0,0,0,2,2,1,1,2]
31+
*/

TwoPointers/75_SortColors.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@
44

55
class Solution(object):
66
def sortColors(self, nums):
7-
"""
8-
:type nums: List[int]
9-
:rtype: void Do not return anything, modify nums in-place instead.
10-
"""
117
len_n = len(nums)
128
# pos_put_0: next position to put 0
139
# pos_put_2: next position to put 2
@@ -29,5 +25,7 @@ def sortColors(self, nums):
2925

3026
"""
3127
[0]
28+
[1,0]
29+
[0,1,2]
3230
[1,1,1,2,0,0,0,0,2,2,1,1,2]
3331
"""

0 commit comments

Comments
 (0)