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.

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?

 


題目標簽:Array

 

  這道題目給了我們一個顏色的array,讓我們sort一下,按照0,1,2的順序。根據題目要求,我們只能遍歷array一次,可以用到two pointers來實現。設一個指針red 在開頭,blue 在最后。想法就是,遇到紅色0,就交換,把0放到最左邊去;遇到藍色2就交換,把2都放到最右邊去,這樣1就會被保留在最中間。需要注意的是,當把藍色2交換完畢之后,需要i--, 停留 i 在原地一次,因為還需要繼續檢查 被2交換回來的數字。那當遇到紅色0,交換完畢不需要停留i 的原因是, 交換回來的只可能是1,對於1,我們不需要做任何處理,直接過就可以。
 
 
 

Java Solution:

Runtime beats 55.91% 

完成日期:07/24/2017

關鍵詞:Array

關鍵點:用two pointers,一頭一尾放置紅色和藍色,保留白色在中間

 

 

 1 public class Solution 
 2 {
 3     public void sortColors(int[] nums) 
 4     {
 5         int red = 0;
 6         int blue = nums.length-1;
 7         
 8         for(int i=0; i<=blue; i++)
 9         {
10             if(nums[i] == 0) // if find 0, swap with red pointer
11             {
12                 int temp = nums[i];
13                 nums[i] = nums[red];
14                 nums[red] = temp;
15                 
16                 red++;
17             }
18             else if(nums[i] == 2) // if find 2, swap with blue pointer
19             {
20                 int temp = nums[i];
21                 nums[i] = nums[blue];
22                 nums[blue] = temp;
23                 
24                 i--;
25                 blue--;
26             }
27        
28         }
29     }
30 }

參考資料:

http://www.cnblogs.com/grandyang/p/4341243.html

 

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM