[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)

从零开始的力扣(第三天)~

1.存在重复元素

给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:
输入: [1,2,3,1]
输出: true

示例 2:
输入: [1,2,3,4]
输出: false

示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
—————————————————————————————————————————

1.将数组进行排列,查询是否有邻项相同

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        nums.sort()
        for i in range(len(nums) - 1):
            if nums[i] == nums[i + 1]:
                return True
            else:
                continue
        return False

[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)

2.巧妙使用set()函数

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) > len(set(nums)):
            return True
        else:
            return False

[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)
set()函数:
[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)

2.只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:
输入: [2,2,1]
输出: 1

示例 2:
输入: [4,1,2,1,2]
输出: 4
—————————————————————————————————————————

1.最偷鸡的方法,使用count()函数

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            if nums.count(nums[i]) < 2:
                return nums[i]
            else:
                continue

[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)
时间复杂度很高,count()函数:
[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)

2.进行删除递归

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            this_num = nums.pop()
            if this_num not in nums:
                return this_num
            else:
                nums.remove(this_num)

[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)

3.使用异或逻辑符(深刻感觉到大佬是真的????????)

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = 0
        for num in nums:
            a = a ^ num
        return a

[leetcode] Python(3)--存在重复元素(217)、只出现一次的数字(136)
异或操作符中有几个知识点:

  1. 0与a异或等于a。
  2. a与a异或等于0。
  3. 数字在进行异或时是在二进制下进行的。

以上就是今日经验!