首页 > 试题广场 >

数组中只出现一次的两个数字

[编程题]数组中只出现一次的两个数字
  • 热度指数:111169 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
一个整型数组里除了两个数字只出现一次,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

数据范围:数组长度 ,数组中每个数的大小
要求:空间复杂度 ,时间复杂度

提示:输出时按非降序排列。
示例1

输入

[1,4,1,6]

输出

[4,6]

说明

返回的结果中较小的数排在前面     
示例2

输入

[1,2,3,3,2,9]

输出

[1,9]
思路简单,就是定义一个hash表,存每个数及出现的次数,当这个数再次出现时,把这个数从表里删除,最后排序输出
class Solution:
    def FindNumsAppearOnce(self , nums: List[int]) -> List[int]:
        # write code here
        result = dict()
        for num in nums:
            if num in result:
                result.pop(num)
            else:
                result[num] = 1

        return sorted(result.keys())


编辑于 2024-04-17 20:41:56 回复(0)
class Solution:
    def FindNumsAppearOnce(self , nums: List[int]) -> List[int]:
        r = 0
        for i in nums:
            r ^= i
        r2 = r&-r
        a,b = 0,0
        for i in nums:
            if r2 & i:
                a ^= i
            else:
                b ^= i
        return [a,b] if a <= b else [b,a]
不必非找第一个1,找出不同即可
编辑于 2024-03-27 13:37:52 回复(0)
from collections import Counter
class Solution:
    def FindNumsAppearOnce(self , nums: List[int]) -> List[int]:
        counter = Counter(nums)
        return sorted([counter.most_common()[-2:][0][0], counter.most_common()[-2:][1][0]])

编辑于 2024-03-19 21:28:51 回复(0)
class Solution:
    def FindNumsAppearOnce(self , array: List[int]) -> List[int]:
        res = []
        for num in array:
            if num in res:
                res.remove(num)
            else:
                res.append(num)
        res.sort()
        return res
发表于 2022-10-04 16:07:48 回复(1)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#

# @param array int整型一维数组 
# @return int整型一维数组
#
class Solution:
    def FindNumsAppearOnce(self , array ):
        # write code here
        return sorted([i for i in array if array.count(i)==1])
发表于 2021-08-09 16:39:22 回复(3)

问题信息

上传者:牛客301499号
难度:
6条回答 5453浏览

热门推荐

通过挑战的用户

查看代码