-
2.22
- 用 while 控制 i
- 当 当前位置为 2 时,交换过来后i 先别动,要检查从右边递过来的数是不是 0 或 1
-
2.5
- 0 放左指针左,2 放右指针右
class Solution {
public void sortColors(int[] nums) {
int low=0,i=0,high=nums.length-1;
while(i<=high){
if(nums[i]==0){
swap(nums,i,low);
low++;
i++;
}else if(nums[i]==2){
swap(nums,i,high);
high--;
}else{
i++;
}
}
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}遍历时:
- 如果
nums[i] == 0→ 交换到low前面,low++、i++ - 如果
nums[i] == 2→ 交换到high后面,high--(注意:i不递增) - 如果
nums[i] == 1→ 跳过,i++