【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

转载于:https://www.cnblogs.com/GoodRnne/p/10925443.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值