颜色分类

public void sortColors(int[] nums){
int zero = -1;
int two = nums.length;

for(int i = 0; i < two; ){
if(nums[i] == 1){
i ++;
}else if(nums[i] == 2){
two --;
swap(nums,i,two);
}else { //nums[i] == 0
zero ++;
swap(nums,zero,i);
i ++;
}
}
}
private void swap(int[] nums, int i, int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}

https://leetcode-cn.com/problems/sort-colors/

来源LeetCode75号题目-颜色分类,具体解题要求,官网上详见。

posted @ 2020-07-29 17:48  文所未闻  阅读(157)  评论(0编辑  收藏  举报