【Leetcode】之Sort Colors
来源:互联网 发布:淘宝客推广公司 编辑:程序博客网 时间:2024/06/08 14:34
一.问题描述
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.
二.我的解题思路
这道题挺特殊的,我采用的是很简单的解法。先遍历整个vector,得到0,1,2的个数,然后再遍历一次进行赋值即可。这种做法的时间复杂度是O(n),但是需要遍历整个数组两次才行。测试通过的程序如下:
class Solution {public: void sortColors(vector<int>& nums) { int len = nums.size(); int num0,num1,num2; num0=num1=num2=0; for(int i=0;i<len;i++){ if(nums[i]==0) num0++; if(nums[i]==1) num1++; if(nums[i]==2) num2++; } int idx[3]={0,num0,num0+num1}; for(int i=0;i<len;i++){ if(i<num0) nums[i]=0; if(i>=num0 && i<(num0+num1)) nums[i]=1; if(i>=(num0+num1)) nums[i]=2; } } };后来又在网上看到别人比较牛逼的思路:
class Solution {public:void sortColors(vector<int>& A) {int len = A.size();int i = -1;int j = -1;int k = -1;for (int p = 0; p < len; p++){//根据第i个数字,挪动0~i-1串。if (A[p] == 0){A[++k] = 2; //2往后挪A[++j] = 1; //1往后挪A[++i] = 0; //0往后挪}else if (A[p] == 1){A[++k] = 2;A[++j] = 1;}elseA[++k] = 2;}}};这种思路是判断0,1,2需要往后挪动的次数,只需要遍历整个数组一次即可。
0 0
- LeetCode之Sort Colors
- LeetCode之Sort Colors
- leetcode之Sort Colors
- LeetCode 之 Sort Colors
- 【Leetcode】之Sort Colors
- Leetcode之Sort Colors 问题
- LeetCode 之 Sort Colors — C 实现
- 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
- HttpURLConnection用法详解
- Dandelion - Eclipse Lisp Plugin
- View的事件分发二
- LeetCode刷题系列(九)Dynamic Programming(2)Longest Subxxxx
- 获取汉字拼音
- 【Leetcode】之Sort Colors
- 理解ImageLoader的原理
- 之前好好的 JLink SWD can not enter debug mode
- 写论文时,给目录和正文分别设置从1开始的页码
- Java/Android对象的四中引用类型 (对象的强、软、弱和虚引用)
- 九度OJ 1096 日期差值(经典)
- 使用HTML5的链接预取功能(link prefetching)给网站提速
- Android使用SQLite数据库的简单例子
- swift-4 数据的存储以及转换