LeetCodeRemove Duplicates from Sorted Array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCodeRemove 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].

/**
 * MyCode
 */
int Function(int *arr,int len)
{
    int newlen = len;

    for(int i = 1;i < newlen; i++)
    {
        int flag = 0;
        for(int j = 0;j < i; j++)
        {
            if(arr[j] == arr[i])
            {
                flag = 1;
                break;
            }
        }

        if(flag == 1)
        {
            for(int k = i+1;k < newlen; k++)
            {
                arr[k-1] = arr[k];
            }
            newlen--;
        }
    }

    return newlen;
}

  

//标准答案

int Function1(int *arr,int len)
{
    int index = 0;
    for(int i = 1;i < len;i++)
    {
        if(arr[index] != arr[i])
            arr[++index] = arr[i];
    }
    return index + 1;
}

  




以上是关于LeetCodeRemove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

leetcodeRemove Duplicates from Sorted Array(easy) /java

LeetcodeRemove Invalid Parentheses

LeetCodeRemove Nth Node From End of List

26Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array