75. Sort Colors

2020-03-10  本文已影响0人  7ccc099f4608

https://leetcode-cn.com/problems/sort-colors/

image.png

(图片来源https://leetcode-cn.com/problems/sort-colors/

日期 是否一次通过 comment
2020-03-10 0

// low: 第一个非0; cur: now; high: 第一个非2

 // [1,0,2,0]
    public void sortColors(int[] nums) {
        if(nums == null || nums.length<2) {
            return;
        }

        int low = 0, cur = 0;
        int high = nums.length-1;
        while(cur <= high) {
            if(nums[cur] == 0) {
                // swap A[i] and A[low] and i,low both ++
                swap(nums, cur++, low++);
            } else if(nums[cur] == 2) {
                //swap A[i] and A[high] and high--;
                swap(nums, cur, high--);

            } else {
                cur++;
            }
        }
    }

    private void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
上一篇下一篇

猜你喜欢

热点阅读