[LeetCode]26.RemoveDuplicatesfromSortedArray

26. Remove Duplicates from Sorted Array

成都创新互联是一家专业提供阳信企业网站建设,专注与网站制作、成都网站制作、H5建站、小程序制作等业务。10年已为阳信众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

题意:

根据给定的排序数组,删除重复元素,并返回删除重复元素后数组的长度。但是申请额外的空间。


思路:

1)如果数组长度为1或者为0,直接返回。

2)把数组的当前位置元素与后一位置元素进行对比,如果相等,无需做什么;如果不相同,那么把不重复数组标示nLen加一,并把第二个替换。

3)*(nums + nLen) = *(nums + cnt + 1)语句说明:如果没出现重复元素,那么nLen == cnt + 1;如果出现重复元素,那么nLen就是重复元素位置,用不重复元素cnt + 1替换即可(比如1,2,2,3此时2,3第一个元素是重复元素,替换即可)

int removeDuplicates(int* nums, int numsSize)
{
    if ( numsSize == 1 || numsSize == 0 ) 
    {   
        return numsSize;
    }   
    /* 1 2 2 3 4*/
    int cnt  = 0;
    int nLen = 0;
    for ( cnt = 0; cnt < numsSize - 1; cnt += 1 ) 
    {   
        if ( *(nums + cnt) != *(nums + cnt + 1) )
        {   
            nLen += 1;
            *( nums + nLen ) = *(nums + cnt + 1); 
        }   
    }   
    return nLen + 1;
}

网站栏目:[LeetCode]26.RemoveDuplicatesfromSortedArray
链接分享:https://www.cdcxhl.com/article34/jhsspe.html

成都网站建设公司_创新互联,为您提供面包屑导航搜索引擎优化云服务器做网站Google网站维护

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设