public class Solution { public int RemoveDuplicates(int[] nums) { var len = nums.Length; if (len == 0) { return 0; } else { var pre = nums[0]; var diffindex = 0; for (int i = 1; i < nums.Length; i++) { if (pre != nums[i]) { nums[++diffindex] = nums[i]; pre = nums[i]; } } return diffindex + 1; } } }
python实现如下:
1 class Solution: 2 def removeDuplicates(self, nums: List[int]) -> int: 3 s = set() 4 n = len(nums) 5 count = 0 6 i,j = 0,0 7 while i < n: 8 if len(s) == 0 or nums[i] not in s: 9 s.add(nums[i]) 10 nums[j] = nums[i] 11 i += 1 12 j += 1 13 count += 1 14 else: 15 i += 1 16 return count
不实用额外的空间,实现如下:
1 class Solution: 2 def removeDuplicates(self, nums: 'List[int]') -> int: 3 n = len(nums) 4 i = 0 5 j = i + 1 6 count = 0 7 while i < n: 8 while j < n and nums[i] == nums[j]: 9 j += 1 10 count += 1 11 if i + 1 < n and j < n: 12 nums[i+1] = nums[j] 13 i += 1 14 else: 15 return count 16 return count