Sorts Colors
来源:互联网 发布:2016 mac pro强制重启 编辑:程序博客网 时间:2024/06/05 23:52
题目描述
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.
题目解答
解题思路
- 先统计red , white, blue 三组颜色的个数,然后分别按照颜色的个数建立数组
- 双指针法
代码实现
- 计数排序
public class Solution { public void sortColors(int[] nums) { if(nums == null || nums.length == 0) return ; int redCount = 0, whiteCount = 0, blueCount = 0; for(int i = 0; i < nums.length; i++){ switch(nums[i]){ //红色 case 0: redCount++; break; case 1: whiteCount++; break; case 2: blueCount++; break; default: } } for(int i = 0; i < nums.length; i++){ if(redCount > 0){ nums[i] = 0; redCount--; }else if(whiteCount > 0){ nums[i] = 1; whiteCount--; }else { nums[i] = 2; } } }}
双指针法
public class Solution { /** *双指针 一个redPos, 一个bluePos */ public void sortColors(int[] nums) { if(nums == null || nums.length == 0) return ; int redPos = 0, bluePos = nums.length-1; int i = 0; while(i <= bluePos){ if(nums[i] == 0){ //0交换回来的只能是1 所以直接加 swap(nums, redPos, i); redPos++; }else if(nums[i] == 2){ //2交换回来的可能是0 所以要继续判断 swap(nums, bluePos, i); bluePos--; continue; } i++; } } public void swap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }}
0 0
- Sorts Colors
- sorts-colors
- colors
- colors
- colors
- Colors
- sorts(disk)及sorts(memory)的意义
- 110 - Meta-Loopless Sorts
- UVaOJ110---Meta-Loopless Sorts
- 110Meta-Loopless Sorts
- uva110 - Meta-Loopless Sorts
- Sorts of Useful Articles
- 13 -> 0 sorts(memory)
- UVA110Meta-Loopless Sorts
- uva 110 - Meta-Loopless Sorts
- uva 110 - Meta-Loopless Sorts
- UVa 110 - Meta-Loopless Sorts
- uva 110 - Meta-Loopless Sorts
- 5分钟带你了解什么是MEMS
- arm_linux学习笔记
- [leetcode] 3. Longest Substring Without Repeating Characters
- 单词首字母大写,删除多余空格
- (转载)Deep Learning(深度学习)学习笔记整理系列之(七)
- Sorts Colors
- MySQL索引及优化
- 郁闷的gxg
- Android的Handler、MessageQueue、Runnable和Looper的联系(源码选自21版本)
- 路径规划算法初探
- Java Web SSH-Spring Hibernate Struts SSH三大框架整合概述
- (转载)Deep Learning(深度学习)学习笔记整理系列之(八)
- Android官方文档翻译 二 1.Building Your First App
- 正则表达式一