Leetcode 75. Sort Colors

来源:互联网 发布:大唐双龙传知乎 编辑:程序博客网 时间:2024/05/16 17:13


    public void sortColors(int[] nums) {        //conor case        if(nums == null || nums.length < 1){            return;        }                //two pointers        int slow = 0;        int fast = nums.length - 1;                //for loop and seperate them        int i = 0;        while(i < nums.length){ // <span style="font-family: Arial, Helvetica, sans-serif;"> && i <= fast -- not necessary</span>            if(nums[i] == 0 && i > slow){                swap(nums, slow, i);                slow++;            }else if(nums[i] == 2 && i < fast){                swap(nums, fast, i);                fast--;            }else{                i++;            }        }            }        void swap(int[] nums, int a, int b){        int temp = nums[a];        nums[a] = nums[b];        nums[b] = temp;    }

refer: https://discuss.leetcode.com/topic/10495/share-one-pass-java-solution/2



0 0