zoukankan      html  css  js  c++  java
  • 【leetcode-75】 颜色分类

    (1过,解法不好,看參考荷兰国旗问题解法)

    给定一个包含红色、白色和蓝色,一共 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

    此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

    注意:
    不能使用代码库中的排序函数来解决这道题。

    示例:

    输入: [2,0,2,1,1,0]
    输出: [0,0,1,1,2,2]

    进阶:

      • 一个直观的解决方案是使用计数排序的两趟扫描算法。
        首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
      • 你能想出一个仅使用常数空间的一趟扫描算法吗?

    我的:双指针都在前

        public void sortColors(int[] A) {
            int redindex = 0;
            int whiteindex = 0;
            int temp1=0;
            for (int i=0;i<A.length;i++) {
                if (A[i] == 0) {
                    temp1 = A[redindex];
                    A[redindex] = A[i];
                    A[i] = temp1;
                    redindex++;
                    if (A[i] != 1)
                    whiteindex++;
                }
                if (A[i] == 1) {
                    temp1 = A[whiteindex];
                    A[whiteindex] = A[i];
                    A[i] = temp1;
                    whiteindex++;
                }
            }
        }

    参考:双指针一前一后

    链接:https://www.nowcoder.com/questionTerminal/4345e55fdb03498a89a97ec18e62b3ab
    来源:牛客网
    
    //荷兰国旗问题,基本思路是,遍历数组跟中间值1做比较,主要有以下两步:
    //1、设置最后一个连续0的位置索引(从前往后),设置第一个连续2的位置索引(从后往前)
    //2、如果遍历到0,就交换,此时不用考虑交换后的ind位置的值(因为如果后面还有0会继续替换),
    //如果遇到2,需要与连续2的位置索引交换,但此时ind不能++(因为如果++后面就没有机会和2的索引位置交换值了)
    class Solution {
    public:
        void sortColors(int A[], int n) {
            int zeroInd = 0,twoInd = n-1;
            for(int ind=0;ind<=twoInd;ind++)
            {
                if(A[ind]==0)
                {
                    A[ind] = A[zeroInd];
                    A[zeroInd] = 0;
                    zeroInd++;
                }else if(A[ind]==2)
                {
                    A[ind] = A[twoInd];
                    A[twoInd] = 2;
                    twoInd--;
                    ind--;
                }
            }
        }
    };
  • 相关阅读:
    xml和web Server以及Remoting
    web窗体的基本控件
    迭代器
    .net 细节问题
    Linq笔记
    .net基础概念理解
    Gridview 和DetailsView FormView细节注意
    .net 基础学习(vs2008 3.5框架)
    一、多线程基础
    CentOS 7和SpringBoot下的Redis配置
  • 原文地址:https://www.cnblogs.com/twoheads/p/10646935.html
Copyright © 2011-2022 走看看