美文网首页
75. Sort Colors

75. Sort Colors

作者: 7ccc099f4608 | 来源:发表于2020-03-10 15:30 被阅读0次

    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;
        }

    相关文章

      网友评论

          本文标题:75. Sort Colors

          本文链接:https://www.haomeiwen.com/subject/cbgwdhtx.html