2015年9月27日星期日

Leetcode 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.
Solution 1: use quick sort 3 way partition, time complexity is O(n);
 public class Solution {  
   public void sortColors(int[] nums) {  
     int n=nums.length;  
     int i=0, j=-1, k=n-1;//quick sort 3-way partition  
     while (i<=k) {  
       if (nums[i]==1) i++;  
       else if (nums[i]==0) swap(nums,i++,++j);  
       else swap(nums,i,k--);  
     }  
   }  
   private void swap(int[] nums, int i, int j) {  
     int temp=nums[i];  
     nums[i]=nums[j];  
     nums[j]=temp;  
   }  
 }  

没有评论:

发表评论