题目:

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?

题解:

这道题就是运用指针来解决了,可以说叫3指针吧。

一个指针notred从左开始找,指向第一个不是0(红色)的位置;一个指针notblue从右开始往左找,指向第一个不是2(蓝色)的位置。

然后另一个新的指针i指向notred指向的位置,往后遍历,遍历到notred的位置。

这途中需要判断:

当i指向的位置等于0的时候,说明是红色,把他交换到notred指向的位置,然后notred++,i++。

当i指向的位置等于2的时候,说明是蓝色,把他交换到notblue指向的位置,然后notred--。

当i指向的位置等于1的时候,说明是白色,不需要交换,i++即可。

代码如下:

 1     public static void swap(int A[], int i, int j){
 2         int tmp = A[i];
 3         A[i]=A[j];
 4         A[j]=tmp;
 5     }
 6     
 7     public static void sortColors(int A[]) {
 8         if(A == null || A.length==0)
 9             return;
             
         int notred=0;
         int notblue=A.length-1;
          
         while (notred<A.length&&A[notred]==0)
             notred++;
             
         while (notblue>=0&&A[notblue]==2)
             notblue--;
          
         int i=notred;
         while (i<=notblue){
             if (A[i]==0) {
                 swap(A,i,notred);
                 notred++;
                 i++;
             }else if (A[i]==2) {
                 swap(A,i,notblue);
                 notblue--;
             }else
                 i++;
         }
     }

最新文章

  1. thinkphp访问不存在的模块或者方法跳转到404页面
  2. UVa 11361 - Investigating Div-Sum Property
  3. Intent七大属性
  4. iOS篇之有沙盒缓存
  5. sqlserver临时表排序问题
  6. FileStream的使用
  7. 987654321 problem - SGU 107(找规律)
  8. activiti笔记一:流程图xml文件
  9. Dockerfile centos7_php5.6.36
  10. Android:困扰了我一个晚上的问题 Failed to resolve: com.android.support:recyclerview-v7.25.3.1
  11. [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)
  12. mybatis教程1(基本使用)
  13. 从零开始学习html(三) 认识标签(第二部分)
  14. vmware自定义网段
  15. Elasticsearch增删改查
  16. Dream_Spark-----Spark 定制版:003~Spark Streaming(三)
  17. LA 3266 田忌赛马
  18. Node.js中的express框架获取http参数
  19. vue-router教程二(要素篇之新手入门)
  20. Squid代理服务器(三)——ACL访问控制

热门文章

  1. OpenCV 基础笔记
  2. Mybatis 源码分析之事物管理
  3. Swift2.0语言教程之闭包
  4. QT学习笔记3:QT中语法说明
  5. Metasploit小技巧
  6. java的多线程之四(线程的操作)
  7. 【10.7校内测试】【队列滑窗】【2-sat】【贪心+栈二分+线段树(noip模拟好题)】【生日祭!】
  8. 学习JavaEE,对比ASP.NET顿悟出一点点道理
  9. jQuery动画高级用法(上)——详解animation中的.queue()函数
  10. maven 自动部署到 tomcat7