zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    kvm虚拟机网络管理
    kvm虚拟机存储管理
    kvm虚拟机迁移
    KVM嵌套虚拟化nested之CPU透传
    kvm认识和安装
    博客美化(二)
    日志管理
    IP分为五类
    windows(xshell)免密码登录
    mpvue的toast弹窗组件-mptosat
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4868948.html
Copyright © 2011-2022 走看看