1. 程式人生 > >LeetCode系列(五)-Remove Duplicates from Sorted Array II

LeetCode系列(五)-Remove Duplicates from Sorted Array II

turn tco duplicate 條件 i++ ica 刪除 count code

  給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素最多出現兩次,返回移除後數組的新長度。

  不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。

示例:

  給定 nums = [0,0,1,1,1,1,2,3,3],

  函數應返回新長度 length = 7, 並且原數組的前五個元素被修改為 0, 0, 1, 1, 2, 3, 3 。

  你不需要考慮數組中超出新長度後面的元素。

解法:

1.思路:創建一個計數器來記錄是否重復兩次,創建一個指針來記錄長度。

public int removeDuplicates(int[] nums) {
        
if (nums.length==0) return 0; int length = 0; int count = 1; for (int i = 1; i < nums.length; i++) { if (nums[i-1]!= nums[i]) { length++; nums[length] = nums[i]; count = 1; } else if (count<2) { length
++; nums[length] = nums[i]; count++; } } return length+1; }

LeetCode系列(五)-Remove Duplicates from Sorted Array II