[LeetCode]26. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear onlyonceand 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 arraynums=[1,1,2]
,
Your function should return length =2
, with the first two elements ofnumsbeing1
and2
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第一个元素是重复元素,替换即可)
intremoveDuplicates(int*nums,intnumsSize){if(numsSize==1||numsSize==0){returnnumsSize;}/*12234*/intcnt=0;intnLen=0;for(cnt=0;cnt<numsSize-1;cnt+=1){if(*(nums+cnt)!=*(nums+cnt+1)){nLen+=1;*(nums+nLen)=*(nums+cnt+1);}}returnnLen+1;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。