LeetCode.75 Sort Colors

来源:互联网 发布:惠阳政府网络问政 编辑:程序博客网 时间:2024/06/05 05:56

题目:

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.


分析:

 class Solution {    public void sortColors(int[] nums) {       //经典红白蓝排序(相邻的颜色在一起),用012分别代表红白蓝       //思路:采用两边分别插入0和2        int index0=0,index2=nums.length-1;        for(int i=0;i<=index2;i++){            if(nums[i]==0&&i!=index0){                //如果该位置为0,将0赋值给index0的位置                //将index0的值交换给i的位置,下次还是再判断i位置                nums[i--]=nums[index0];                nums[index0++]=0;            }else if(nums[i]==2&&i!=index2){                nums[i--]=nums[index2];                nums[index2--]=2;            }        }    }}


原创粉丝点击