找到数组中唯一不重复的元素

题目

Given a list of numbers, where every number shows up twice except for one number, find that one number.

Example:
Input: [4, 3, 2, 4, 1, 3, 2]
Output: 1

Challenge: Find a way to do this using O(1) memory.

分析

要实现 O(1) 空间复杂度,能学到的一个简单办法是就地将数组排个序。然后2个2个的迭代,判断相邻2个元素是否相等,不相等则找到了唯一元素。
时间复杂度上升到了至少 O(nlogn). (但如果用计数排序的话,也许可以做到 O(n), 但是这样一来空间复杂度又不满足了)。

代码

def singleNumber(nums):
    nums.sort()
    for i in range(0, len(nums) - 1, 2):
        if nums[i + 1] != nums[i]:
            return nums[i]

print singleNumber([4, 3, 2, 4, 1, 3, 2])
# 1

猜你喜欢

转载自www.cnblogs.com/new-start/p/11664655.html