C# One pass


  • 0
    C
    public class Solution {
        public void SortColors(int[] nums) {
            int index0 = 0, index2 = nums.Length - 1;
            for(int i = 0; i <= index2; i++)
            {
                if(nums[i] == 0 && i != index0)        //if it's 0, swap to left
                {
                    nums[i--] = nums[index0];          //stay at the same index for next round
                    nums[index0++] = 0;
                }
                else if(nums[i] == 2)        //if it's 2, swap to right
                {
                    nums[i--] = nums[index2];
                    nums[index2--] = 2;
                }
            }
        }
    }
    

Log in to reply
 

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