Sort Colors
来源:互联网 发布:剑网三炮哥捏脸数据 编辑:程序博客网 时间:2024/06/07 13:45
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三个数字,给数组排序但是不允许使用库函数
思路:先指定两个索引,分别指向数组的前后两端,从左边找一个不为0的数字和在右边找出第一个为0的数字,然后交换这两个数字,直到交换完,此时数组的分为两部分,前面的数字为0,后面的部分数字非0,然后排后面一半的数字,以同样的方法来交换1和2,直到交换完所有的1和2,此时数组排序就排好了。
代码如下:
public class Solution { public void sortColors(int[] A) { int length = A.length; int i = 0; int j = length - 1; while (i < j ) { while (i<length && A[i] == 0) i++; while (j>=0 && A[j] != 0) j--; if (i < j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } } int k = j + 1; int s = length - 1; while (k < s) { while (k<length&&A[k] == 1) k++; while (s>=0 && A[s] != 1) s--; if (k < s) { int temp = A[k]; A[k] = A[s]; A[s] = temp; } } }}
0 0
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Java的国际化(i18n)
- struts2中XML配置中result的值
- 树链剖分模板
- 第八周 项目一(3):实现复数类中的运算符重载(扩充类)
- [Matlab] 使用GPU进行滤波运算
- Sort Colors
- python2.7和python3.4网络编程处理二进制数据区别
- 2015.4.22.20.46_ecilipse_8.30_Eclipse 10个最有用的快捷键_0.01
- Problem 37—Truncatable primes
- 黑马程序员—异常小知识点整理
- 使用Spring实现异常统一处理【二】
- next_permutation(,,) C++全排列
- jquery获取checkbox的value
- dubbo源码阅读笔记--动态扩展