[LeetCode]Sort Colors
来源:互联网 发布:证券开户数据 编辑:程序博客网 时间:2024/05/18 01:38
Question
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?
本题难度Medium。
交换法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
有个简单的方法,在follow up已经说了:分别计算出0、1、2的个数,然后对nums重新赋值。不过它要跑两趟(two-pass algorithm)。如何一趟搞定?
我们用三个指针:left、i、right。left是0的边界(left所在的元素可以为0也可以不为0),i为待处理元素,right是2的边界(同理,right所在的元素可以为2也可以不为2)。对于num[i]
的处理:
num[i]==1
,不进行交换,i++num[i]==0
,swap(left,i),left++,i++num[i]==2
,swap(right,i),right–
简而言之,就是把 0 往前扔,把 2 往后扔即可。
【附】
【注意】
i要从0开始而不能从1开始,否则对于:
nums=[2 1]
会失败。
【代码】
public class Solution { public void sortColors(int[] nums) { //require int size=nums.length; int left=0,right=size-1; //invariant int i=0; while(i<=right){ if(nums[i]==0){ swap(left++,i,nums); i++; }else if(nums[i]==2){ swap(right--,i,nums); }else{ i++; } } } private void swap(int i,int j,int[] nums){ int tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; }}
- 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
- Android常见面试题
- hrbust 1797 Fly【Tarjan强连通+缩点染色+最长路SPFA】好题~
- Android产品研发(十七)-->Hybrid开发
- CSS布局中居中(水平/垂直/水平垂直)问题的总结
- JavaScript中你所不知道的数组ArrayBuffer
- [LeetCode]Sort Colors
- 第88篇 webrtc一对一IOS端研究(一)及php及JS
- 银联支付集成-android studio
- 欢迎使用CSDN-markdown编辑器
- 差分约束系统 糖果Candy
- Java 内存区域划分
- Android产品研发(十八)-->webview问题集锦
- bzoj 1656: [Usaco2006 Jan] The Grove 树木 (bfs+技巧)
- 数据结构实验之二叉树二:遍历二叉树