这道题要注意循环条件
class Solution {
public void sortColors(int[] nums) {
if (nums.length == 0 || nums == null){
return;
}
int start = 0;
int end = nums.length - 1;
for(int i=0; i<= end; i++){
if(nums[i] == 0) {
swap(nums, i, start);
start++;
} else if (nums[i] == 2){
swap(nums, i, end);
end--;
i--;
}
}
return;
}
public void swap(int[]nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
本文提供了一种解决荷兰国旗问题的有效方法,通过调整数组中0、1、2三种颜色的位置来实现排序。此算法使用了双指针技巧,分别从数组的开始和结束位置向中间移动,最终达到在单次遍历内完成排序的目标。
3115

被折叠的 条评论
为什么被折叠?



