Update 荷兰国旗.md

add C++ Code
This commit is contained in:
程序员鱼皮 2021-04-26 17:17:19 +08:00 committed by GitHub
parent b470e3d12f
commit f51ee922d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -72,6 +72,8 @@
下面我们直接看代码吧和三向切分基本一致
Java Code
```java
class Solution {
public void sortColors(int[] nums) {
@ -99,6 +101,37 @@ class Solution {
}
```
C++ Code
```c++
class Solution {
public:
void sortColors(vector<int>& nums) {
int len = nums.size();
int left = 0;
//这里和三向切分不完全一致
int i = left;
int right = len-1;
while (i <= right) {
if (nums[i] == 2) {
swap(nums,i,right--);
} else if (nums[i] == 0) {
swap(nums,i++,left++);
} else {
i++;
}
}
}
void swap (vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
};
```
另外我们看这段代码有什么问题呢那就是我们即使完全符合时仍会交换元素这样会大大降低我们的效率
例如[0,0,0,1,1,1,2,2,2]
@ -117,6 +150,8 @@ class Solution {
另一种代码表示
Java Code
```java
class Solution {
public void sortColors(int[] nums) {
@ -148,5 +183,38 @@ class Solution {
}
```
C++ Code
```c++
class Solution {
public:
void sortColors(vector<int>& nums) {
int left = 0;
int len = nums.size();
int right = len - 1;
for (int i = 0; i <= right; ++i) {
if (nums[i] == 0) {
swap(nums,i,left);
left++;
}
if (nums[i] == 2) {
swap(nums,i,right);
right--;
//如果不等于 1 则需要继续判断所以不移动 i 指针i--
if (nums[i] != 1) {
i--;
}
}
}
}
void swap (vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
};
```
好啦这个问题到这就结束啦是不是很简单啊我们明天见