Easy Understand Java Solution


  • 0
    W
    public void sortColors(int[] nums) {
            int start = 0, end = nums.length - 1;
            for (int i = 0; i <= end; i++) {
                if (nums[i] == 0) {
                    nums[i] = nums[start];
                    nums[start] = 0;
                    start++;
                } else if (nums[i] == 2) {
                    nums[i] = nums[end];
                    nums[end] = 2;
                    i--;
                    end--;
                }
            }
        }
    

  • 0
    E

    why it need i-- in the last two line


  • 0
    W
    This post is deleted!

  • 0
    W

    @ericsungmi

    because above code is a swap
    but if you put your end to current index, you still need judge that value, so you need i-- to rejudge that value

    like this case
    Input:
    [1,2,0]
    if we don't do i--; then will got
    Output:
    [1,0,2]
    Expected:
    [0,1,2]
    so we need rejudge '0' to put it to start

    Swap start value needn't do i--, because if start is '2' will trigger end branch if start is '1' will put to mid so it' ok, like this case "2,1,0,0,0,2,2"


  • 0
    E

    @wudizhuo
    Thx


Log in to reply
 

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