Sort Colors 颜色排序(只有3类值的排序)
来源:互联网 发布:java互联网面试题 编辑:程序博客网 时间:2024/06/05 10:09
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.
---------------------------------------------------------------------------------------------------------------------------------------------------------
这个问题实质上就是对于0, 1, 2的序列进行排序。由于只有3类值。
我们可以实现一个时间复杂度为 O ( n ) , 空间复杂度为 O ( 1 )的算法。
核心的思想是:
将0 的全都放到left边, 将2 的全都放到right边,
最后,就是排好序的了。
为了实现这个思想,
我们需要有一个left 指针,和一个right指针。
让left指针前面的都是0, right指针后面的都是1。
同时一个cur指针,从左到右遍历这个数组。
1. cur 遍历到0的时候,我们将0 与 left 指向的值互换。left++;
2. 当cur遍历到2的时候,我们将2 与right指向的值互换,right--;
3. 当cur遍历到1的时候,cur++, 不用管,继续往下走。
4. 注意:如果0已经放在符合要求的位置了,left++, cur++
如果2已经放在符合要求的位置了,说明后面的都是2了,可以结束了。
运行时间:
代码:
public void sortColors(int[] nums) { if (nums == null || nums.length == 0 || nums.length == 1) { return; } int left = 0; int right = nums.length - 1; int cur = left; while (cur <= right) { if (nums[cur] == 0) { if (cur == left) {// already on the right place cur++; left++; } else { nums[cur] = nums[left];// swap nums[left] = 0; left++; } } else if (nums[cur] == 1) { cur++; } else if (nums[cur] == 2) { if (cur == right) {// already on the right place, can return return; } nums[cur] = nums[right]; nums[right] = 2;// swap right--; } } }
- Sort Colors 颜色排序(只有3类值的排序)
- [leetcode 75] Sort Colors-----------只有三种颜色的排序
- Sort Colors 颜色排序
- LeetCode 75 Sort Colors(颜色排序)
- LeetCode 75. Sort Colors(颜色排序)
- LeetCode--Sort Colors(颜色排序)Python
- Sort Colors 排序颜色 @LeetCode
- leetcode:sort colors排序颜色
- LeetCode OJ 之 Sort Colors(颜色排序)
- [Java语言] Sort Colors 颜色排序
- [LeetCode] Sort Colors 按颜色排序
- 【排序】Sort Colors
- LeetCode Sort Colors(排序)
- Sort Colors 三色排序
- LeetCode-Sort Colors-排序
- leetCode 75.Sort Colors (颜色排序) 解题思路和方法
- leetcode 75. Sort Colors-颜色排序|双指针
- Leetcode刷题记——75. Sort Colors(颜色排序)
- 括号最大匹配(区间dp)
- 基数排序 java代码实现
- 远程linux服务器Tomcat中重新集成详解
- 一款类似天天音乐软件的源码分享
- 推荐参考vim配置文件-c/c++
- Sort Colors 颜色排序(只有3类值的排序)
- Photoshop测量角度
- 数论专题
- spring+mybatis轻量级企业框架的学习之路之错误笔记day04
- git branch操作
- date和dateformat练习
- ios初学SQLite3(创建、插入、查询、更新数据库和表)
- Netty Client重连实现
- boost库------>unordered_set(散列容器)