荷兰国旗问题
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size(), l = 0, r = n-1;
while(l < r){
while(l < n && nums[l] == 0) l++;
while(r > 0 && nums[r] != 0) r--;
if(l < r) swap(nums[l], nums[r]);
}
r = n-1;
while(l < r){
while(l < n && nums[l] == 1) l++;
while(r > 0 && nums[r] == 2) r--;
if(l < r) swap(nums[l], nums[r]);
}
}
};
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size(), p = 0, q = n-1, k = n-1;
while(p < q){
while(p < n && nums[p] == 0) p++;
while(q > 0 && nums[q] != 0) q--;
while(k > 0 && nums[k] == 2) k--;
if(p < q){
swap(nums[q], nums[k]);
swap(nums[p], nums[k]);
}
}
while(p < k){
while(p < n && nums[p] != 2) p++;
while(k > 0 && nums[k] == 2) k--;
if(p < k) swap(nums[p], nums[k]);
}
}
};
class Solution {
public:
void sortColors(vector<int>& nums) { // 此方法步幅为1,有冗余操作
int n = nums.size(), l = 0, r = n-1, cur = 0;
while(cur <= r){
if(!nums[cur]) swap(nums[l++], nums[cur++]);
else if(nums[cur] == 2) swap(nums[cur], nums[r--]);
else cur++;
}
}
};
————————————————————————————————————————
package main
import (
"{pathToYourApp}/cmd"
)
func main() {
cmd.Execute()
}