75. Sort Colors

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.

public class Solution {
    public void sortColors(int[] nums) {
        int n = nums.length;
        if(nums == null||n <= 0)
           return;
        
        int i = 0,j = n-1,k1 = 0,k2 = n-1;
        while(k1<n)
        {
            if(nums[k1]==0)
              {
                  int temp1 = nums[i];
                  nums[i] = nums[k1];
                  nums[k1] = temp1;
                  
                  i++;
              }
            k1++;
        }
        
        while(k2>=0)
        {
            if(nums[k2]==2)
              {
                  int temp2 = nums[j];
                  nums[j] = nums[k2];
                  nums[k2] = temp2;
                  j--;
              }
            k2--;
        }
        
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,811评论 0 23
  • LeetCode 75 Sort Colors Given an array with n objects col...
    ShuiLocked阅读 263评论 0 0
  • Given an array with n objects colored red, white or blue,...
    番茄晓蛋阅读 344评论 0 0
  • 咱们说的佛这个字就是觉者,他对自我分分秒秒内在发生的状态都很清楚,没有一个念头不清楚,没有一个动机不清楚,没有一个...
    helenliu258阅读 84评论 0 0
  • 人长大了总会觉得自己很穷。知识的匮乏,感情的空白,或者金钱的短缺。为了这些我们被迫向前走,去寻找,可是得到的越多,...
    virginiahan阅读 244评论 0 0