Leetcode——remove-element

来源:互联网 发布:淘宝会员打折怎么设置 编辑:程序博客网 时间:2024/05/21 06:17

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

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.


今天在Leetcode上看到的两道题,解法比较相似。现整理如下:

remove-duplicates-from-sorted-array(删除排序数组的重复元素)

remove-element(删除数组中的给定元素)

思路:动态维护一个值index

比如题一:一次遍历整个数组元素,当元素值发生变化时,更新index。输出为新的数组长度。

int removeDuplicates(int A[], int n){    if(A==NULL||n<=0)        return 0;    int newn=0;    int i=0;    while(i<n)    {        if(A[newn]!=A[i])        {            newn++;            A[newn]=A[i];        }        i++;    }    return newn+1;}


注意两题有一点不同的是输出。题一只保留重复元素的一次,题二是删除指定元素。

int removeElement(int A[], int n, int elem) {          int index=0;        int i=0;        while(i<n)        {           if(A[i]!=elem)           {              A[index++]=A[i];            }            i++;        }        return index;}



0 0
原创粉丝点击