题目连接:https://leetcode.com/problems...php
这题是给数组排序,数组里面只有3个变量。一个方法是用相似bucket sort,3个桶,统计三个变量出现的个数,而后重构数组便可。html
// count appears time of each number int[] count = new int[3]; for(int num : nums) count[num]++; int k = 0; for(int i = 0; i < 3; i++) { for(int j = 0; j < count[i]; j++) { nums[k++] = i; } }
还有一种方法是用three way partition,参考算法这本书上的讲解和程序:
http://algs4.cs.princeton.edu...
http://algs4.cs.princeton.edu...java
public class Solution { public void sortColors(int[] nums) { int i = 0, j = nums.length - 1; int pivot = 1; int k = 0; while(k <= j) { if(nums[k] < pivot) swap(nums, i++, k++); else if(nums[k] > pivot) swap(nums, k, j--); else k++; } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }