classSolution {publicvoidsortColors(int[] nums) {// write your code here// put 0 on 1's leftint start =partition(nums,0,1);// then put 1 on 2 left (begin with 0's end)partition(nums, start,2); }privateintpartition(int[] nums,int start,int pivot) {int left = start;int right =nums.length-1;while (left <= right) {while (left <= right && nums[left] < pivot) { left++; }while (left <= right && nums[right] >= pivot) { // equal, 所以最後 left, right 相交, 中間沒東西 right--; }if (left <= right) {swap(nums, left, right); left++; right--; } }return left; }privatevoidswap(int[] nums,int i,int j) {int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }}
The problem is known as Dutch National Flag Problem and first was proposed by Edsger W. Dijkstra. The idea is to attribute a color to each number and then arrange them following the order of colors on the Dutch flag.