leetcode 75. Sort Colors

来源:互联网 发布:python安装包官网下载 编辑:程序博客网 时间:2024/05/22 12:56

75. Sort Colors


问题描述

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.

思路

其实我最初的思路看着我用快速排序就可以直接解决啊,结果真的解决了。

public void sortColors(int []nums) {        //能不能直接利用快速排序的思想        quickSort(nums,0,nums.length - 1);        //当然我们会有更好的方式    }    public void quickSort(int []nums,int lo,int hi) {        if (lo > hi) {            return;        }           int p = partion(nums,lo,hi);        quickSort(nums,lo,p - 1);        quickSort(nums,p + 1,hi);    }    public int partion(int []nums,int lo,int hi) {        int begin = lo - 1;        for (int i = lo;i < hi;i++) {            if (nums[i] < nums[hi]) {                begin++;                if (begin != i) {                    exchange(nums,i,begin);                }            }        }        begin++;        exchange(nums,begin,hi);        return begin;    }    public void exchange(int[] nums,int x,int y) {        int t = nums[x];        nums[x] = nums[y];        nums[y] = t;    }

不过这题并不是考察我们快速排序,这个其实是一个分布排序,因为我们的元素只有0,1,2,快速排序显然是大材小用了,而且快速排序中也有将数组一分为三的情况。这里的思路来自于七月算法公开课,有兴趣的一定要去看看。

0–(i - 1)为0
i–(k-1)为1
k–(j-1)为我们的探测
j–n-1为为2

public void sortColors(int[] nums) {        int i = 0;        int j = nums.length - 1;        for (int k = 0;k <= j;k++) {            if (nums[k] == 0) {                swap(nums,k,i++);            } else if(nums[k] == 2){                swap(nums,k--,j--);            } else {                continue;            }        }    }    public void swap(int[]nums,int x,int y) {        int t = nums[x];        nums[x] = nums[y];        nums[y] = t;    }    public void test1() {        int a[] = {1,2,0,2,1,1};        sortColors(a);        print(a);    }    public void test2() {        int a[] = {1,2,0};        sortColors(a);        print(a);    }
0 0
原创粉丝点击