LeetCode:Sort Colors

来源:互联网 发布:netbeans怎么编写java 编辑:程序博客网 时间:2024/06/06 14:12

推荐参照: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.

  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.

  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?

思路一:

  抛开题目限制,直接调用排序方法,即可实现。

public void sortColors(int[] A) {        Arrays.sort(A);//方法一        }

思路二:

  使用题目中提到的方法,计数然后重新赋值。

public void sortColors(int[] A) {    //方法二:通过计数    int []count_num = new int[] {0,0,0};            for(int i = 0;i<A.length;i++)                count_num[A[i]]++;            count_num[1] += count_num[0];            for(int j=0;j<A.length;j++){                if(j<count_num[0])                    A[j] = 0;                else if(j<count_num[1])                    A[j] = 1;                else                    A[j] = 2;            }                   }

思路三:

  考虑题目要求,one-pass,constant space

  设置3个变量,分别代表数组从前向后遍历的索引zeroindex,当前遍历的索引 i,数组从后向前遍历的索引 twoindex。因此有下列结论:

  • 当A[i]=0时,必须把它移到数组的前面,交换A[i]和A[zeroIndex]的值,然后i++,zeroIndex++即可;
  • 当A[i]=2时,必须把它移到数组的后面,交换A[i]和A[twoIndex]的值,然后twoIndex–,注意此时应执行i–,因为我们交换过去的A[twoIndex]不确定是几,还需要在下次循环里进行判断。
  • 当 A[i]=1时,就不需操作了,因为0和2排好了,1自然就在中间了。
public void sortColors(int[] A) {    int zeroIndex = 0;    int twoIndex = A.length - 1;    for(int i = 0;i < twoIndex + 1;i++){    //边调整位置边缩减范围twoindex        if(A[i] == 0){            A[i] = A[zeroIndex];            A[zeroIndex] = 0;            zeroIndex ++;        }else if(A[i] == 2){            A[i] = A[twoIndex];            A[twoIndex] = 2;            twoIndex --;            i --;        }else{        }    }       }

思路四:

  Just like the Lomuto partition algorithm usually used in quick sort. We keep a loop invariant that [0,i) [i, j) [j, k) are 0s, 1s and 2s sorted in place for [0,k). Here “)” means exclusive. We don’t need to swap because we know the values we want.

  下面介绍Lomuto partitioning方法。

  参考快速排序

  对数组a,设需要划分的其中一段为a[p]-a[r],我们期待的结果是得到一个q,其中p<=q<=r,使得a[p]_a[q-1]<=a[q]<=a[q+1]_a[r],这个时候原先的一段数组被分成了三部分。

public class Solution {    public void sortColors(int[] nums) {        int i = 0,j = 0;        for(int k = 0; k< nums.length;k++){            int temp = nums[k];            nums[k] = 2;            if(temp < 2){                nums[j] = 1;                j++;            }            if(temp == 0){                nums[i] = 0;                i++;            }        }    }}

Any comments greatly appreciated.

0 0
原创粉丝点击