zoukankan      html  css  js  c++  java
  • Color Sort

    问题描述

    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. 

    解决思路

    1. 计数排序;

    2. 双指针法,一遍扫描;

    程序

    1. 普通版本

    public class Solution {
        public void sortColors(int[] nums) {
            if (nums == null || nums.length == 0) {
                return ;
            }
            int begin = 0, end = nums.length - 1;
            while (true) {
                while (begin < end && nums[begin] == 0) {
                    ++begin;
                }
                while (end > begin && nums[end] == 2) {
                    --end;
                }
                if (begin >= end) {
                    break ;
                }
                int p = end;
                while (p >= begin && nums[p] == 1) {
                    --p;
                }
                if (p < begin) {
                    break;
                }
                if (nums[p] == 0) {
                    swap(nums, p, begin);
                } else {
                    swap(nums, p, end);
                }
            }
        }
        
        private void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
    

    2. 精炼版本

    public class Solution {
        public void sortColors(int[] nums) {
            if (nums == null || nums.length == 0) {
                return ;
            }
            int begin = 0, end = nums.length;
            for (int i = 0; i < end; i++) {
                if (nums[i] == 0) {
                    swap(nums, i, begin);
                    ++begin;
                } else if (nums[i] == 2) {
                    --end;
                    swap(nums, i, end);
                    --i; // 交换前面的元素不确定为0或者1
                }
            }
        }
        
        private void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
    

      

  • 相关阅读:
    哈夫曼树
    MUI
    mui.init方法配置
    js中如何把字符串转化为对象、数组示例代码
    ( 转 )超级惊艳 10款HTML5动画特效推荐
    ( 转 ) 关于微信公众号,你不知道的15个小技巧
    h5预加载代码
    css3常用动画样式文件move.css
    iphone微信 h5页音乐自动播放
    sshpass: 用于非交互的ssh 密码验证
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4685014.html
Copyright © 2011-2022 走看看