[leetcode] 75. Sort Colors
来源:互联网 发布:ubuntu 压缩 编辑:程序博客网 时间:2024/06/13 05:26
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.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
解法一:
没看follow up的时候,我觉得奇怪,这道题把0,1,2的个数分别数出来,赋值给nums就完了啊。
这里实现的类似冒泡算法。使用一个辅助变量,记录当前需要交换的位置。一次的rotate 0,1,2。不过不是one pass啊。
class Solution {public: void sortColors(vector<int>& nums) { // rotate 0s int idx = 0, tmp; for(int i=0; i<nums.size(); i++){ if(nums[i]==0){ tmp = nums[i]; nums[i] = nums[idx]; nums[idx] = tmp; ++idx; } } // rotate 1s for(int i=idx; i<nums.size(); i++){ if(nums[i]==1){ tmp = nums[i]; nums[i] = nums[idx]; nums[idx] = tmp; ++idx; } } // rotate 2s for(int i=idx; i<nums.size(); i++){ if(nums[i]==2){ tmp = nums[i]; nums[i] = nums[idx]; nums[idx] = tmp; ++idx; } } }};
解法二:
使用两个idx,一个指向第一个不是0的位置,一个指向倒着看第一个不是2的位置。如果发现0,则交换至idx0指向的位置,idx0后裔以为;如果是2,交换至idx2指向的位置,idx2前移一位,i减1。循环至i==idx2。
class Solution {public: void sortColors(vector<int>& nums) { int idx0 = 0, idx2 = nums.size()-1, tmp; for(int i=0; i<=idx2; i++){ if(nums[i]==0){ swap(nums[i],nums[idx0++]); } else if(nums[i]==2){ swap(nums[i--],nums[idx2--]); } } }};
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 【leetcode】75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- Leetcode 75. Sort Colors
- [LeetCode]75. Sort Colors
- LeetCode 75. Sort Colors
- LeetCode *** 75. Sort Colors
- leetcode 75. Sort Colors
- LeetCode 75. Sort Colors
- leetcode-75. Sort Colors
- [leetcode]75. Sort Colors
- LeetCode-75.Sort Colors
- 当前使用的IP地址有4个字节(32)组成,即IPV4编码方式。每个IP地址包换两部分:网络号和主机号。当分配给主机号的二进制位越多,则能标识的主机数就越多,相应地能标识的网络数就越少,反之亦然。
- 大数相加
- hdu 5832
- 2016.8.9最大流
- 关于GridView加载和滑动时造成的图片混乱问题总结
- [leetcode] 75. Sort Colors
- Trouble-Shooting:CRS未启动导致RAC无法启动的对应方法
- HDU OJ 5283 Senior's Fish
- 【Objective-C】栈(stack)和堆(heap)的区别
- Meet Android Studio
- STL算法(14)——for_each()
- Application Fundamentals
- 勾股定理一日一证连载72
- 2016.08.11【初中部 NOIP提高组 】模拟赛C题解