LeetCode(75):Sort Colors

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.

题意:其实可以简单理解为对只包含0,1,2元素的数组进行排序,不能调用排序的库函数。

思路:由于数组中只包含3个元素,排序的结果为0在数组的左部,1在中部,2在右部。所以可以可以使用双指针分别一个left和一个right分别指向数组的首元素和末尾元素。然后开始遍历,如果遇到0就和left所指的元素交换,left指针加1,如果遇到2就和right所指的元素交换,right指针减1,遇到1就跳过,直到和right相遇。

代码:

public void sortColors(int[] nums) {
       int temp=0;
       int left = 0,right=nums.length-1;
       int i=0;
       while(i<=right){
           if(nums[i]==0){
               temp = nums[i];
               nums[i] =nums[left];
               nums[left] = temp;
               left++;
               i++;
           }else if(nums[i]==2){
               temp = nums[i];
               nums[i] =nums[right];
               nums[right] = temp;
               right--;
           }else {
               i++;
           }
       }
    }
原文地址:https://www.cnblogs.com/Lewisr/p/5161434.html