• 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

  • 相关阅读:
    Centos7 GRE Tunnel
    centos 7 增加永久静态路由
    ceph bluestore与 filestore 数据存放的区别
    swift对象存储安装
    [WebRTC] Audio Codec Encoder 基类注解
    [WebRTC] 源码中的Audio Codec整理
    [Math] Maple函数用法
    [Server] Nginx Https配置 及 Firefox提示“此页面使用较弱加密”
    [Windows] 导出所有设置过的Group Policy
    [Tool] WebDav 安装及使用
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4868948.html
Copyright © 2020-2023  润新知