75 Sort Colors
75. Sort Colors
1. Question
2. Implementation
class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int redIndex = 0, blueIndex = nums.length - 1;
for (int i = 0; i <= blueIndex; i++) {
if (nums[i] == 0) {
swap(nums, i, redIndex);
++redIndex;
}
else if (nums[i] == 2) {
swap(nums, i, blueIndex);
--blueIndex;
--i;
}
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}3. Time & Space Complexity
Last updated