Leetcode 75) Sort Colors
in Algorithms
My Solution
class Solution {
public void sortColors(int[] nums) {
//move 0 to the front, move 2 to the back
//use two for loop, to leverage logic from move zeros.
int zeroInd = 0;
for(int i =0;i<nums.length;i++){
if(nums[i]==0){
swap(i,zeroInd,nums);
zeroInd++;
}
}
int twoInd = nums.length-1;
for(int i=nums.length-1;i>=0;i--){
if(nums[i]==2){
swap(i,twoInd,nums);
twoInd--;
}
}
}
public void swap(int i, int j , int[] nums){
int tmp = nums[i];
nums[i] = nums[j];
nums[j]=tmp;
}
}