Sort colors - Java Solution, one pass O(n)


  • 0
    V
    public class Solution {
        public void sortColors(int[] nums) {
            int z = 0, t = nums.length-1, i;
            for( i=0; i <= t; i++) {
                while( nums[i] == 2 && i<t) {
                    /* swap(nums[i], nums[t--]) */
                    nums[i] = nums[t];
                    nums[t--] = 2;
                }
                while( nums[i] == 0 && i>z) {
                    /* swap(nums[i], nums[z++]) */
                    nums[i] = nums[z];
                    nums[z++] = 0;
                }
            }
        }
    }
    

Log in to reply
 

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