给定一个排序好的数组,将其中重复的元素删除掉
思路: 双指针法,后面的指针只有在前边的指针遇到了新的数值时才向前移动
Python:
123456789101112131415
lass Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ # 5 star if not nums: return 0 j = 0 for i in range(len(nums)): if nums[i] != nums[j]: nums[j+1], nums[i] = nums[i], nums[j+1] j += 1 return j + 1
Go:
func removeDuplicates(nums []int) int { fast, slow := 1, 1 length := len(nums) for fast < length { if nums[fast] == nums[fast-1] { fast++ } else { nums[slow] = nums[fast] slow++ fast++ } } return slow}