From f51ee922d0b09271be66f944ed813486522e66b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98=E9=B1=BC=E7=9A=AE?= <592789970@qq.com> Date: Mon, 26 Apr 2021 17:17:19 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E8=8D=B7=E5=85=B0=E5=9B=BD=E6=97=97.m?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add C++ Code --- .../数据结构和算法/荷兰国旗.md | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/animation-simulation/数据结构和算法/荷兰国旗.md b/animation-simulation/数据结构和算法/荷兰国旗.md index f6ae623..fba8c5c 100644 --- a/animation-simulation/数据结构和算法/荷兰国旗.md +++ b/animation-simulation/数据结构和算法/荷兰国旗.md @@ -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& 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& 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& 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& nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +}; +``` + 好啦,这个问题到这就结束啦,是不是很简单啊,我们明天见!