欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode——remove-duplicates-from-sorted-array(从排序数组中删除重复项)

程序员文章站 2022-04-15 14:10:52
...
1.题目描述

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

题意大概就是:要求不能另外开辟数组保存值,只能在已有的内存空间排序进行操作。

2.结题思路

(1)特殊情况:数组为空或者给定的长度为负数的时候,返回0;
(2)定义两个变量i,j做索引值,j指向数组中下标为0的位置,i指向数组中下标为1的位置:当A[j]!=A[i]的时候,i和j同时向后走,否则i向后走;进行循环。
如下图:
LeetCode——remove-duplicates-from-sorted-array(从排序数组中删除重复项)

3.实现代码
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<=0)return 0;
        int k=0;
        for(int i=1;i<n;i++)
        {
            if(A[k]!=A[i])
            {
                A[++k]=A[i];
            }
        }
        return k+1;
    }
};