題目:
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 by modifying the input array in-place with O(1) extra memory.
Example:
Given 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#define MIN(a,b) (((a)<(b))?(a):(b)) int removeDuplicates(int* nums, int numsSize) { int i = 0,j; int count = MIN(1,numsSize); int idx = 0; int end = numsSize; for(i=1 ; i< end; i++){ if(nums[i-1]==nums[i]){ // 移動元素 for(j=i;j<end;j++){ nums[j-1]=nums[j]; } end--; i--; }else{ count++; } } return count; } |
文章標籤
全站熱搜
