标签:leetcode
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.You are not suppose to use the library‘s sort function for this problem.
思路1:直接遍历数组统计三种颜色的个数然后依次填充,复杂度O(N)
代码1:
public void sortColors1(int[] A) {//统计1,2,3的个数 int [] colorCount = new int[3]; for(int i =0; i < A.length; ++i){ switch (A[i]){ case 0: colorCount[0] ++; break; case 1: colorCount[1] ++; break; case 2: colorCount[2] ++; break; } } int from, i = 0, to = 0; while (i < colorCount.length){ from = to; to = to + colorCount[i]; Arrays.fill(A, from ,to,i); i ++; } }
public void sortColors(int[] A) {//用快速排序的思想, final int RED = 0, WHITE = 1, BLUE = 2; int l =0, r = A.length - 1,mid = l; while (mid <= r){ if(A[mid] == RED){ int temp = A[mid]; A[mid] = A[l]; A[l] = temp; l ++; mid ++; }else if(A[mid] == BLUE){ int temp = A[mid]; A[mid] = A[r]; A[r] = temp; r --; }else { mid ++; } } }
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44900249