zoukankan      html  css  js  c++  java
  • 【LeetCode】26. Remove Duplicates from Sorted Array

    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].

    两个指针,一个ind指向新数组的新位置,一个i遍历原数组,in-place实现。

    使用last记录上一个遍历到的数字。

    如果A[i]与last相等,则跳过。如果A[i]是一个新数字,则赋给A[ind],并且ind前进一位。

    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            if(n == 0)
                return 0;
            int ind = 1;
            int last = A[0];
            for(int i = 1; i < n; i ++)
            {
                if(A[i] != last)
                {
                    A[ind ++] = A[i];
                    last = A[i];
                }
            }
            return ind;
        }
    };

  • 相关阅读:
    0.1.3 set的用法
    JoinPoint
    砝码组合(dfs)
    强大的【环绕通知】
    applicationContext.xml 模板
    各种jar包
    装饰博客(二)添加宠物
    装饰博客(一)添加背景图片
    拖拽功能的实现
    点击之后连接qq
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3750598.html
Copyright © 2011-2022 走看看