码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Remove Duplicates from Sorted Array

时间:2017-12-11 18:39:05      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:ace   hat   log   with   length   mem   ++   fun   blog   

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;
}

  

【LeetCode】Remove Duplicates from Sorted Array

标签:ace   hat   log   with   length   mem   ++   fun   blog   

原文地址:http://www.cnblogs.com/hatsusakana/p/8024021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!