LeetCode算法题解(2)移除重复元素

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

这道题目与前一题Remove Element比较类似。但是在一个排序好的数组里面删除重复的元素。首先我们需要知道,对于一个排好序的数组来说, A[N + 1] >= A[N] ,我们仍然使用两个游标i和j来处理,假设现在i = j + 1,如果A[i] == A[j],那么我们递增i,直到A[i] != A[j],这时候我们再设置A[j + 1] = A[i],同时递增i和j,重复上述过程直到遍历结束。

#include <iostream>
using namespace std;

int removeTwiceMore(int arr[],int n);
int main()
{
    //声明并初始化数组
   int array[]={1,1,1,2,2,3,3,3,4,4,4,4,4};
    //数组长度
    int length=sizeof(array)/sizeof(int);
    int newlength=removeTwiceMore(array,length);
    cout<<"新的数组长度为:"<<newlength;

   return 0;
}

//输入数组,数组长度,返回去重后的数组长度
//因为数组名就是地址,相当于址传递
int removeTwiceMore(int arr[],int n)
{
    int j=0;
    for(int i=1;i<n;i++)
    {
        if(arr[i]!=arr[j])
        {
            arr[++j]=arr[i];
        }
    }
    return j+1;
}

输出:
新的数组长度为:4

猜你喜欢

转载自blog.csdn.net/u014571489/article/details/81189890