leetcode 75. Sort Colors

来源:互联网 发布:哈萨克软件下载 编辑:程序博客网 时间:2024/06/14 04:40

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.

click to show follow up.

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?

我的思路是把所有0赶到最左边,把所有2赶到最右边。
public void sortColors(int[] nums) {int low=0;int high=nums.length-1;while(low<high){while(low<high&&nums[low]==0){low++;}while(low<high&&nums[high]==2){high--;}if(nums[low]==2){swap(nums, low, high);high--;}else if(nums[high]==0){swap(nums, low, high);low++;}else{//nums[low]=1&&nums[high]=1if(low<high){int i=low+1;while(i<high&&nums[i]==1){i++;}if(i<high){if(nums[i]==0){swap(nums, low, i);low++;}else{//nums[i]==2swap(nums, high, i);high--;}}else{//i一直到high都没发现有!=1的数return;}}}}}public void swap(int[] nums,int i,int j){int tmp=nums[i];nums[i]=nums[j];nums[j]=tmp;}
有大神也用的我这个思路,不过方法更加简洁。

The basic idea is to use two pointer low and high and an iterator i

   public void sortColors(int[] A) {       if(A==null || A.length<2) return;       int low = 0;        int high = A.length-1;       for(int i = low; i<=high;) {  //注意for中没有i++           if(A[i]==0) {              // swap A[i] and A[low] and i,low both ++              int temp = A[i];              A[i] = A[low];              A[low]=temp;              i++;low++;           }else if(A[i]==2) {               //swap A[i] and A[high] and high--;              int temp = A[i];              A[i] = A[high];              A[high]=temp;              high--;           }else {               i++;           }       }   }
另外,还有更加简洁的方法:
class Solution {public:    void sortColors(int A[], int n) {        int second=n-1, zero=0;        for (int i=0; i<=second; i++) {            while (A[i]==2 && i<second){            swap(A[i], A[second]);            second--;            }            while (A[i]==0 && i>zero){            swap(A[i], A[zero]);            zero++;            }        }    }};
或者
void sortColors(int A[], int n) {    int j = 0, k = n-1;    for (int i=0; i <= k; i++) {        if (A[i] == 0)            swap(A[i], A[j++]);        else if (A[i] == 2)            swap(A[i--], A[k--]);    }}

需要注意这两者的差别,前者用的 while,后者在swap时用了 i-- 。


原创粉丝点击