【LeetCode每天一题】Single Number(数组中单独的数字)

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

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

思路

  这道题在剑指offer上面也有,最简单的方法就是先将数组进行排序,然后从头开始遍历查找。这样做的时间复杂度为O(nlogn), 空间复杂度为O(1)。还有一个方法就是使用辅助空间,将数组遍历一遍转化成字典,然后找出其中值为1的键就是结果。这种解法的时间复杂度为O(n), 空间复杂度为O(n)。另外最后一种算法是我们利用异或的性质,两个相同的数数字进行异或时,会得到0,因为在数组中除了一个数字之外,其他的都出现了两次,所以当我们对数组中所有数字异或之后,就只剩下一个只出现一次的数字。这种解法的时间复杂度为O(n),空间复杂度为O(1)。
解决代码

 1 class Solution(object):
 2     def singleNumber(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         if not nums:
 8             return 0
 9         res = nums[0]
10         for i in range(1, len(nums)): # 从头开始遍历
11             res = res ^ nums[i]     # 异或
12         return res

猜你喜欢

转载自www.cnblogs.com/GoodRnne/p/10925443.html
今日推荐