zoukankan      html  css  js  c++  java
  • leetcode 之Remove Duplicates from Sorted Array(2)

    描述
        Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
        For example, Given sorted array A = [1,1,1,2,2,3],
        Your function should return length = 5, and A is now [1,1,2,2,3]

        之前的想法是再加一个计数的变量就行了

        

    int removeDeplicates1(int A[], int n)
    {
        int index = 0, count = 1;
        for (int i = 1; i < n; i++)
        {
            if (A[index] != A[i])
            {
                A[index++] = A[i];
                count = 1;
            }
            else 
            {
                if (count <= 2)
                {
                    A[index] = A[i];
                    count++;
                }
            }
        }
    
        return index + 1;
    }

           后来看到了一个更简洁的做法,这个想法很巧妙啊:因为是排好序的,所以只需拿第三个和第一个比,不同的话保存即可。

    int removeDeplicates1(int A[], int n)
    {
        int index = 2;
        for (int i = 2; i < n; i++)
        {
            if (A[index-2] != A[i])
            {
                A[index++] = A[i];
            }
            
        }
    
        return index;
    }
  • 相关阅读:
    vim 真是上瘾啊
    乐此不疲
    .vimrc .bashrc
    github
    隐藏c语言烦人的{ }
    linux mint console-setup
    samsung n143 brightness on linux mint
    荒漠甘泉——1月31日
    嵌入式 方向?
    python2与python3的区别
  • 原文地址:https://www.cnblogs.com/573177885qq/p/5451089.html
Copyright © 2011-2022 走看看