|
74 | 74 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
75 | 75 |
|
76 | 76 | ```python
|
77 |
| - |
| 77 | +class Solution: |
| 78 | + def sortColors(self, nums: List[int]) -> None: |
| 79 | + """ |
| 80 | + Do not return anything, modify nums in-place instead. |
| 81 | + """ |
| 82 | + i, j = -1, len(nums) |
| 83 | + cur = 0 |
| 84 | + while cur < j: |
| 85 | + if nums[cur] == 0: |
| 86 | + i += 1 |
| 87 | + nums[cur], nums[i] = nums[i], nums[cur] |
| 88 | + cur += 1 |
| 89 | + elif nums[cur] == 1: |
| 90 | + cur += 1 |
| 91 | + else: |
| 92 | + j -= 1 |
| 93 | + nums[cur], nums[j] = nums[j], nums[cur] |
78 | 94 | ```
|
79 | 95 |
|
80 | 96 | ### **Java**
|
81 | 97 |
|
82 | 98 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
83 | 99 |
|
84 | 100 | ```java
|
| 101 | +class Solution { |
| 102 | + public void sortColors(int[] nums) { |
| 103 | + int i = -1, j = nums.length; |
| 104 | + int cur = 0; |
| 105 | + while (cur < j) { |
| 106 | + if (nums[cur] == 0) { |
| 107 | + swap(nums, cur++, ++i); |
| 108 | + } else if (nums[cur] == 1) { |
| 109 | + ++cur; |
| 110 | + } else { |
| 111 | + swap(nums, cur, --j); |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + private void swap(int[] nums, int i, int j) { |
| 117 | + int t = nums[i]; |
| 118 | + nums[i] = nums[j]; |
| 119 | + nums[j] = t; |
| 120 | + } |
| 121 | +} |
| 122 | +``` |
| 123 | + |
| 124 | +### **C++** |
| 125 | + |
| 126 | +```cpp |
| 127 | +class Solution { |
| 128 | +public: |
| 129 | + void sortColors(vector<int>& nums) { |
| 130 | + int i = -1, j = nums.size(), cur = 0; |
| 131 | + while (cur < j) { |
| 132 | + if (nums[cur] == 0) { |
| 133 | + swap(nums[++i], nums[cur++]); |
| 134 | + } else if (nums[cur] == 1) { |
| 135 | + ++cur; |
| 136 | + } else { |
| 137 | + swap(nums[cur], nums[--j]); |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | +}; |
| 142 | +``` |
85 | 143 |
|
| 144 | +### **Go** |
| 145 | +
|
| 146 | +```go |
| 147 | +func sortColors(nums []int) { |
| 148 | + i, j, cur := -1, len(nums), 0 |
| 149 | + for cur < j { |
| 150 | + if nums[cur] == 0 { |
| 151 | + i++ |
| 152 | + nums[cur], nums[i] = nums[i], nums[cur] |
| 153 | + cur++ |
| 154 | + } else if nums[cur] == 1 { |
| 155 | + cur++ |
| 156 | + } else { |
| 157 | + j-- |
| 158 | + nums[cur], nums[j] = nums[j], nums[cur] |
| 159 | + } |
| 160 | + } |
| 161 | +} |
86 | 162 | ```
|
87 | 163 |
|
88 | 164 | ### **...**
|
|
0 commit comments