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--;
                }
            }
        }
    }
  • 相关阅读:
    Bootstrap-table一个表格组件神器(学习二)实战
    JS基础_for循环练习3
    JS基础_for循环练习2
    JS基础_for循环练习1
    JS基础_for循环
    JS基础_while的练习2
    JS基础_while的练习1
    JS基础_while循环
    JS基础_条件分支语句:switch语句
    JS基础_if注意问题
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7275211.html
Copyright © 2011-2022 走看看