zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted Array 分类: Leetcode(线性表) 2015-03-25 16:10 35人阅读 评论(0) 收藏

    Remove Duplicates from Sorted Array

    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    For example,
    Given input array A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].


    一开始一直在想对于重复的元素该怎么操作,想到用两个指针,一前一后,重复的话跳过,结果这样搞把问题搞复杂了,反向思路,我们只要不同的的元素,因此只对不同的操作。

    class Solution {
    public:
        int removeDuplicates(int a[], int n) {
            int i, index;
            if(n==0) return 0;
            i=1;
            index=0;
            while(i<n) {
                if(a[index] != a[i])
                    a[++index] = a[i];
                i++;
            }
            return index+1;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    sql number类型和varchar2类型
    B
    E
    D
    B
    A
    第三课 选区
    第二课 新建文件与图层
    第一课 界面认识
    CSS命名规则
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656947.html
Copyright © 2011-2022 走看看