1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public void sortColors(int[] nums) { int zeroIndex = 0, twoIndex = nums.length - 1;
int i = 0; while (i <= twoIndex) { if (nums[i] == 0) { swap(nums, i++, zeroIndex++); } else if (nums[i] == 2) { swap(nums, i, twoIndex--); } else { i++; } } }
private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
|