Skip to content

Latest commit

 

History

History
63 lines (53 loc) · 1.7 KB

80.md

File metadata and controls

63 lines (53 loc) · 1.7 KB

80. Remove Duplicates from Sorted Array II

在 Remove Duplicates from Sorted Array(从一个有序的数组中去除重复的数字,返回处理后的数组长度) 的基础上,可以使每个数字最多重复一次,也就是说如果某一个数字的个数大于等于2个,结果中应保留2个该数字。

思路:有点类似双指针,一前一后,后边的保存想要的结果,前边的向前遍历,记录每个数字出现的次数,次数大于2就直接忽略了,前边的继续前进,次数小于等于2则将其放在j+1的索引上,并将j前进一位

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 6 star, 
        if len(nums) < 3:
            return len(nums)
        count = 1
        j = 0
        for i in range(1, len(nums)):
            if nums[i] == nums[j]:
                if count == 2:
                    pass
                else:
                    count += 1
                    nums[j+1] = nums[i]
                    j += 1
            else:
                count = 1
                nums[j+1] = nums[i]
                j += 1
        return j + 1

Go:

// 3 star, 类似第26题,只是加一个变量考虑重复的次数
func removeDuplicates(nums []int) int {
	length := len(nums)
	if length <= 1 {return length}
	count := 1
	realLength := 1
	for index, val := range nums {
		if index > 0 && nums[index] != nums[index-1] {
			count = 1
			nums[realLength] = val
			realLength++
		} else if index > 0 && nums[index] == nums[index-1]{
			if count < 2 {
				nums[realLength] = nums[index]
				count++
				realLength++
			}

		}
	}
	return realLength


}