LeetCode 75. 颜色分类
class Solution { public void sortColors(int[] nums) { // [0,zero) = 0 ; [zero,i) = 1; [two,nums.length - 1] = 2 //保证循环开始时[0,zero)为空,所以设置zero 为 -1,遍历时先加,后交换 int zero = -1; //未来保证初始化时[two,nums.length - 1] 为空,将two 设置为nums.length,遍历时先减,再交换 int two = nums.length; int i = 0; //当i = two 时,上面的三个子区间正好覆盖全部数组,因此循环可以继续的条件是 i < two; while(i < two){ if(nums[i] == 0){ zero++; swap(nums,i,zero); i++; }else if(nums[i] == 1){ i++; }else{ two--; swap(nums,i,two); } } } public void swap(int[] nums,int index1,int index2){ int tmp = nums[index1]; nums[index1] = nums[index2]; nums[index2] = tmp; } }