標籤: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