码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode Sort Colors

时间:2016-08-19 13:13:56      阅读:103      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!