• Leetcode Sort Colors


    Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

    Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

    Note:
    You are not suppose to use the library's sort function for this problem.

    click to show follow up.

    Follow up:
    A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

    Could you come up with an one-pass algorithm using only constant space?


    解题思路:

    One pass 简而言之,遇到0,交换到前面,遇到2, 交换到后面。用双指针left, right来记录当前已经就位的0序列和2序列的边界位置。
    假设已经完成到如下所示的状态:
     
    0......0   1......1  x1 x2 .... xm   2.....2
                  |           |               |
                left        cur          right
     
    (1) A[cur] = 1:已经就位,cur++即可
    (2) A[cur] = 0:交换A[cur]和A[left]。由于A[left]=1或left=cur,所以交换以后A[cur]已经就位,cur++,left++
    (3) A[cur] = 2:交换A[cur]和A[right],right--。由于xm的值未知,cur不能增加,继续判断xm。
         cur > right扫描结束。

    Java code:
    public class Solution {
        public void sortColors(int[] nums) {
            if(nums == null || nums.length < 2) {
                return;
            }
            int left = 0, right = nums.length-1;
            int i = 0;
            while( i <= right) {
                if(nums[i] == 0) {
                    swap(nums, i, left);
                    i++;
                    left++;
                }else if(nums[i] == 1) {
                    i++;
                }else if(nums[i] == 2) {
                    swap(nums, i, right);
                    right--;
                }
            }
        }
        
        private void swap(int[] nums, int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

    Reference:

    1. http://bangbingsyb.blogspot.com/2014/11/leetcode-sort-colors.html

  • 相关阅读:
    Adobe PS
    深入学习二叉树(04)平衡二叉树
    深入学习二叉树(03)二叉查找树
    C 知识点
    实战【docker 镜像制作与使用】
    从0到1了解 CI/CD
    单例模式的几种实现方式,使用场景以及优缺点
    设计模式之策略模式浅谈以及简单例子
    WPF几种渐变色
    Linq学习以及简单用法
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4868948.html
Copyright © 2020-2023  润新知