Skip to content

Commit

Permalink
add: weekly 394
Browse files Browse the repository at this point in the history
  • Loading branch information
binacs committed Aug 3, 2024
1 parent cf30b0c commit 1ac72d6
Show file tree
Hide file tree
Showing 12 changed files with 680 additions and 102 deletions.
82 changes: 45 additions & 37 deletions basic/basic-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,61 +451,39 @@ inline void radix_sort(unsigned A[], int len)
> [!TIP] **思路**
>
>
> BFPRT
<details>
<summary>详细代码</summary>
<!-- tabs:start -->
##### **C++**
##### **C++ 标准**
```cpp
class Solution {
public:
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[l];
while (l < r) {
while (r > l && nums[r] >= pivot) -- r ;
nums[l] = nums[r];
while (r > l && nums[l] <= pivot) ++ l ;
nums[r] = nums[l];
}
nums[l] = pivot;
return l;
}
int findKthLargest(vector<int>& nums, int k) {
int l = 0, r = nums.size() - 1;
int tar = r - k + 1;
while (l < r) {
int idx = partition(nums, l, r);
if (idx < tar) l = idx + 1;
else r = idx;
}
return l < nums.size() ? nums[l] : -1;
}
};
// yxc version 1
class Solution {
public:
int quick_sort(vector<int>& nums, int l, int r, int k) {
if (l == r) return nums[k];
int x = nums[l], i = l - 1, j = r + 1;
// k 保持不变 持续缩小范围
int quick_sort(vector<int> & nums, int l, int r, int k) {
if (l >= r) // ATTENTION
return nums[k];
int i = l - 1, j = r + 1, x = nums[l + r >> 1];
while (i < j) {
do i ++ ; while (nums[i] > x);
do i ++ ; while (nums[i] > x); // ATTENTION >
do j -- ; while (nums[j] < x);
if (i < j) swap(nums[i], nums[j]);
if (i < j)
swap(nums[i], nums[j]);
}
if (k <= j) return quick_sort(nums, l, j, k);
else return quick_sort(nums, j + 1, r, k);
if (k <= j)
return quick_sort(nums, l, j, k);
else
return quick_sort(nums, j + 1, r, k);
}
int findKthLargest(vector<int>& nums, int k) {
return quick_sort(nums, 0, nums.size() - 1, k - 1);
}
};
// yxc version 2
class Solution {
public:
int quick_sort(vector<int> & nums, int l, int r, int k) {
Expand All @@ -515,7 +493,8 @@ public:
while (i < j) {
do i ++ ; while (nums[i] > x);
do j -- ; while (nums[j] < x);
if (i < j) swap(nums[i], nums[j]);
if (i < j)
swap(nums[i], nums[j]);
}
if (j - l + 1 >= k)
return quick_sort(nums, l, j, k);
Expand All @@ -529,6 +508,35 @@ public:
};
```

##### **C++ 废弃**

```cpp
class Solution {
public:
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[l];
while (l < r) {
while (r > l && nums[r] >= pivot) -- r ;
nums[l] = nums[r];
while (r > l && nums[l] <= pivot) ++ l ;
nums[r] = nums[l];
}
nums[l] = pivot;
return l;
}
int findKthLargest(vector<int>& nums, int k) {
int l = 0, r = nums.size() - 1;
int tar = r - k + 1;
while (l < r) {
int idx = partition(nums, l, r);
if (idx < tar) l = idx + 1;
else r = idx;
}
return l < nums.size() ? nums[l] : -1;
}
};
```
##### **Python**
```python
Expand Down
Loading

0 comments on commit 1ac72d6

Please sign in to comment.