首页 > 其他 > 详细

LintCode Sort Colors

时间:2016-08-19 13:12:31      阅读:160      评论:0      收藏:0      [点我收藏+]

技术分享技术分享

For this problem we need to sort the array into three parts namely with three numbers standing for three different colors. Currently, the method in mind could be statistically get all the frequency of three numbers by screening the whole list. However, the chanllenge is to do it in O(N) time with extra O(1) storage. So, we want to use three pointers.

The two pointers used named as seperators to seperate the number which is less than 1 and larger than 1. When encountered the number less than 0 pl and i both increase. Because pl is pointing to the first element which is not 0.

 

class Solution {
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */
    public void sortColors(int[] a) {
        int pl = 0;
        int pr = a.length - 1;
        int i = 0;
        while (i <= pr) {
            //pl could be view as the first index which is not 0
            //every time after judge of two numbers i++ and pl++ if it is
            //not 0
            if (a[i] == 0) {
                swap(a,pl,i);
                pl++;
                i++;
            }
            else if (a[i] == 1) {
                i++;
            }
            //pr could be viwe as the first index which is not 2
            else {
                swap(a,pr,i);
                pr--;
            }
        }
    }
    
    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

 

LintCode Sort Colors

原文:http://www.cnblogs.com/ly91417/p/5786838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!