[LeetCode][Java] Sort Colors

來源:互聯網
上載者:User

標籤:leetcode   java   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?

題意:

給定一組分別具有紅白藍顏色的對象,重新排序他們使得相同顏色的對象相鄰。排序後的順序是紅白藍。

這裡我們用 0, 1, and 2 來分別表示紅白藍三個顏色。

注意:不能用庫中的排序函數。

演算法分析:

方法一:

三指標的方法,類似於快速排序

left = 0,指標right = n-1;一次遍曆,如果遇到0,交換給left,遇到2,交換給right,遇到1別管。

方法二:

下面是比較low的一種方法,但是比較好理解
分別統計0,1,2的個數,對數組重新進行賦值

 AC代碼:

public class Solution {    public void sortColors(int[] A)     {        if (A == null || A.length == 0) return;        int left = 0;        int right = A.length - 1;        int cur = left;                while(cur <= right)        {        if (A[cur] == 0)         {        swap(A, left++, cur);        cur = (cur <= left) ? left : cur;        }         else if (A[cur] == 2)         {        swap(A, right--, cur);        }         else         {        cur++;        }        }    }    public void swap(int[] A, int i, int j)     {        int temp = A[i];        A[i] = A[j];        A[j] = temp;    }}

方法二:

public class Solution{    public void sortColors(int[] A)     {        int count0 = 0;int count1 = 0;int count2 = 0;for(int i = 0; i < A.length; i++){if(A[i] == 0){count0++;}if(A[i] == 1){count1++;}if(A[i] == 2){count2++;}}for(int i = 0; i < count0; i++){A[i] = 0;}for(int i = count0; i < count0+count1; i++){A[i] = 1;}for(int i = count0+count1; i < count0+count1+count2; i++){A[i] = 2;}    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Sort Colors

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.