Leetcode面试题56 - I. 数组中数字出现的次数——python求解

面试题56 - I. 数组中数字出现的次数

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

示例 1:

输入:nums = [4,1,4,6]
输出:[1,6][6,1]
示例 2:

输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10][10,2]
限制:

2 <= nums <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof

#暴力求解:
class Solution(object):
    def singleNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        ans = dict()
        for num in nums:
            if num in ans.keys():
                ans[num] += 1
            else:
                ans[num] = 1
        res = []
        for an in list(ans.keys()):
            if ans[an] == 1:
                res.append(an)
        return res

猜你喜欢

转载自blog.csdn.net/weixin_41729258/article/details/105809908