two point and one-pass solution with Java


  • 0
    M

    public void sortColors(int[] nums) {
    // the first method use two point to represent 0 and 1 resprectively
    // index0 shows the current 0 should locate the pos
    // index1 shows the current 1 should locate the pos
    if(nums == null || nums.length == 0) return;
    int index0 = 0;
    int index1 = 0;
    //int i = 0;
    for(int i = 0; i < nums.length; i++) {
    if(nums[i] == 0) {
    nums[i] = 2;
    nums[index1++] = 1;
    nums[index0++] = 0;
    } else if(nums[i] == 1) {
    nums[i] = 2;
    nums[index1++] = 1;
    }
    }
    return;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.