26.Remove duplicate from Sorted Array

【leetcode】---数组题目【python】

思路:题目不允许开辟新空间,且数组排好序。若nums[i]==nums[index-1],增加i去避免复制。当nums[i]!=nums[index-1],此时进行复制,且让index+1,重复操作直至i达到len(nums)

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        index = 1
        for i in range(1,len(nums)):
            if nums[i] != nums[index-1]:  #找出与nums[index-1]不相等的数组下标i
                nums[index]=nums[i]    #不同值赋值给num[index]
                index += 1       #此处index+1便于下次赋值,恰好为不重复数组长度
        return index

80.Remove Depulicates from Sorted Array II

【leetcode】---数组题目【python】

思路:同上,重点在于改成判断nums[i]与nums[index-2]

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)<=2:
            return len(nums)
        index = 2
        for i in range(2,len(nums)):
            if nums[i]!=nums[index-2]:
                nums[index] = nums[i]
                index +=1
        return index

【leetcode】---数组题目【python】

思路一:暴力**

思路二:先排序

思路三:去掉重复元素,在分别从两边扩散

相关文章:

  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-04
  • 2021-09-19
猜你喜欢
  • 2021-06-27
  • 2022-12-23
  • 2021-06-19
  • 2022-02-17
  • 2021-11-28
  • 2022-12-23
  • 2021-10-15
相关资源
相似解决方案