LeetCode:Sort Colors
来源:互联网 发布:侯振挺落选院士 知乎 编辑:程序博客网 时间:2024/06/05 09:38
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library’s sort function for this problem.
思路1:
- 题目和荷兰国旗问题是相同的
- 采用三个指针start,mid,end来操作,依据nums[mid]的值来判断下一步的操作
- 当nums[mid]=0时,swap(nums[start],nums[mid]),start++,mid++
- 当nums[mid]=1时,mid++
- 当nums[end]=2时,swap(num[end],nums[mid]) end–
思路2:
- 三指针赋值更新办法
这种方法很巧妙,自己动手走一个例子,慢慢理解
#include "stdafx.h"#include "iostream"#include "vector"using namespace std;class Solution {public: //方法2 void sortColors(vector<int>& nums) { int two = 0, one = 0, zero = 0; for (int num : nums) { if (num == 2) { two++; } if (num == 1) { nums[two++] = 2; nums[one++] = 1; } if (num == 0) { nums[two++] = 2; nums[one++] = 1; nums[zero++] = 0; } } } //方法1 void sortColor(vector<int>& nums) { //the second solution int start = 0, end = nums.size() - 1, mid=0,tmp; while (mid <= end) { if (nums[mid] == 0) { //swap(nums[start++], nums[mid++]); tmp = nums[start]; nums[start] = nums[mid]; nums[mid] = tmp; mid++; start++; } else if (nums[mid] == 1) { mid++; } else if (nums[mid] == 2) { //swap(nums[mid], nums[end--]); tmp = nums[end]; nums[end] = nums[mid]; nums[mid] = tmp; end--; } } }};int main(){ vector<int> nums; nums.push_back(2); nums.push_back(2); nums.push_back(1); nums.push_back(0); nums.push_back(2); Solution sol; sol.sortColor(nums); for (int i=0; i < nums.size(); i++) cout << nums[i] << endl; system("pause"); return 0;}
阅读全文
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- github中创建自己的cocoapod私有库_异常问题解决
- 【Java邮件开发】7.邮件的基本格式与编码
- 软件设计六大原则
- hiho第151周 Building in Sandbox floodfill
- 初等排序之插入排序
- LeetCode:Sort Colors
- SpringBoot开发详解(八) -- 使用Swagger2构建API文档
- 生成器
- 《Boost》Part1 Minimum Spanning Tree
- 迭代器
- input 标签disabled问题
- ecnu
- 欢迎使用CSDN-markdown编辑器
- 《软考设计模式之题型》