26. 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 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; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。