LintCode Sort Colors

LintCode Sort ColorsLintCode Sort Colors

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 = ;
int pr = a.length - ;
int i = ;
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] == ) {
swap(a,pl,i);
pl++;
i++;
}
else if (a[i] == ) {
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;
}
}
上一篇:[原]pomelo开发环境搭建


下一篇:【特别推荐】几款极好的 JavaScript 下拉列表插件