Leetcode75. Sort Colors

先用partition的思想做了一下,发现其实根本不需要那么复杂,只是用了partition的左右双指针的思想而已。

class Solution {
    public void sortColors(int[] nums) {
        if(nums==null|nums.length<2) return;
        
        int left = 0,right = nums.length-1;//left represent position for next 0;right for next 2
        int index = 0;
        while(index<=right){
            if(nums[index]==0) {
                swap(nums,index,left++);
            }
            if(nums[index]==2) {
                swap(nums,index,right--);
                index--;    //important
            }
            index++;
        }
    }
    private void swap(int[] n,int a,int b){
        int temp = n[a];
        n[a] = n[b];
        n[b] = temp;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sort Colors.
Memory Usage: 37.3 MB, less than 54.03% of Java online submissions for Sort Colors.

posted @ 2019-03-27 10:47  大胖子球花  阅读(60)  评论(0)    收藏  举报