zoukankan      html  css  js  c++  java
  • [leetcode]75.Sort Color三指针

    import java.util.Arrays;
    
    /**
     * 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?
     */
    /*
    * 两种解法
    * 1.三个指针:红指针,蓝指针,遍历指针(循环指针i),红蓝指针比别从前后端记录红色区域和蓝色区域的边界位置,
    * 遍历指针负责找到红蓝颜色的数据,白色的不用管,最后中间剩下的就是白色
    * 2.记录红白蓝三色出现的次数,最后直接对数组进行相应的赋值
    * 这里选用第一种
    * 容易出错的地方:遍历指针和边界指针交换之后,还要在遍历指针的位置再判断一下是不是其他颜色,
    * 所以比较适合写成两个if分别判断,而且后边的if要加i--*/
    public class Q75SortColors {
        public static void main(String[] args) {
            int[] nums = new int[]{2,2,2};
            sortColors(nums);
            System.out.println(Arrays.toString(nums));
        }
        public static void sortColors(int[] nums) {
            int red = 0;
            int blue = nums.length - 1;
            int temp;
            //获取红色区域的初始边界
            for (int i =0;i < nums.length;i++)
            {
                if (nums[i] != 0)
                {
                    red = i;
                    break;
                }
                
            }
            //获取蓝色区域的初始边界
            for (int i =nums.length-1;i >= 0 ;i--)
            {
                if (nums[i] != 2)
                {
                    blue = i;
                    break;
                }
    
            }
            //遍历交换归位
            for (int i =red;i <= blue ;i++)
            {
                if (nums[i] == 0)
                {
                    temp = nums[red];
                    nums[red] = nums[i];
                    nums[i] = temp;
                    red++;
                }
                if (nums[i] == 2)
                {
                    temp = nums[blue];
                    nums[blue] = nums[i];
                    nums[i] = temp;
                    blue--;
                    i--;
                }
            }
        }
    }
  • 相关阅读:
    Centos-ip配置详解
    Selenium-java-js操作日历
    Selenium-java-获取当前时间
    一起学ROS之启动文件及ROS命令汇总
    一起学ROS之通信机制
    一起学ORBSLAM2(1)跑通ORBSLAM2 ubuntu 14.04的运行
    高斯金字塔的思考
    ubuntu下opencv2.4.9和opencv3.1.0的使用
    一起学ROS之安装ROS(ubuntu+ros+opencv2.4.9+kinect V2 安装教程)
    动态规划解决分层图最短路径问题
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7275211.html
Copyright © 2011-2022 走看看