1. 程式人生 > >[leetcode]75.Sort Color三指針

[leetcode]75.Sort Color三指針

出現 only code red nbsp use 而且 imp 遍歷

import java.util.Arrays;

/**
 * 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?
 
*/ /* * 兩種解法 * 1.三個指針:紅指針,藍指針,遍歷指針(循環指針i),紅藍指針比別從前後端記錄紅色區域和藍色區域的邊界位置, * 遍歷指針負責找到紅藍顏色的數據,白色的不用管,最後中間剩下的就是白色 * 2.記錄紅白藍三色出現的次數,最後直接對數組進行相應的賦值 * 這裏選用第一種 * 容易出錯的地方:遍歷指針和邊界指針交換之後,還要在遍歷指針的位置再判斷一下是不是其他顏色, * 所以比較適合寫成兩個if分別判斷,而且後邊的if要加i--*/ public class Q75SortColors { public static void main(String[] args) {
int[] nums = new int[]{2,2,2}; sortColors(nums); System.out.println(Arrays.toString(nums)); } public static void sortColors(int[] nums) { int red = 0; int blue = nums.length - 1; int temp; //獲取紅色區域的初始邊界 for (int i =0;i < nums.length;i++) {
if (nums[i] != 0) { red = i; break; } } //獲取藍色區域的初始邊界 for (int i =nums.length-1;i >= 0 ;i--) { if (nums[i] != 2) { blue = i; break; } } //遍歷交換歸位 for (int i =red;i <= blue ;i++) { if (nums[i] == 0) { temp = nums[red]; nums[red] = nums[i]; nums[i] = temp; red++; } if (nums[i] == 2) { temp = nums[blue]; nums[blue] = nums[i]; nums[i] = temp; blue--; i--; } } } }

[leetcode]75.Sort Color三指針