LeetCode-75. Sort Colors
来源:互联网 发布:油画淘宝详情页模版 编辑:程序博客网 时间:2024/06/06 03:00
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.
类似于快速排序的算法。
class Solution {public: void sortColors(int A[], int n) { int left=0; int right=n-1; int i=0; while(i<=right){ if(A[i]==0){ swap(A[left],A[i]); left++; i++; } else if(A[i]==1){ i++; } else{ swap(A[right],A[i]); right--; } } }};
2017-12-1更新
官网上有个提示,是个很直接的方法,思路:
1、第一次遍历数组,将其中0.1.2的数量记录下来。
2、第二遍遍历数组,用记录下来0.1.2的数量给数组赋值。
Java实现
class Solution { public void sortColors(int[] nums) { int[] count = {0,0,0}; for(int i=0;i<nums.length;++i) { if(nums[i]==0) count[0]++; else if(nums[i]==1) count[1]++; else count[2]++; } for(int i=0;i<count[0];++i) nums[i]=0; for(int i=0;i<count[1];++i) nums[count[0]+i]=1; for(int i=0;i<count[2];++i) nums[count[0]+count[1]+i]=2; }}
阅读全文
0 0
- [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
- 回文数问题
- 手机淘宝app这是怎么了,这是什么bug,还真没有见过。
- 遇到一个全新的需求项目,怎么办?
- input框中的文字加下划线
- Hive创建表
- LeetCode-75. Sort Colors
- Spring Boot将WAR文件部署到Tomcat
- 最小的K个数的多种解法
- 二叉树的序列化
- axios 使用文档
- Jenkins启动slave的方法
- Effective STL 24 Choose carefully between map::operator[] and map::insert
- 设计模式的应用场景(11)--组合模式
- 记录一次自定义参数绑定错误问题的解决过程