1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第一百三十六题
(1)题目
英文:
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?
中文:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
(2)解法
① 使用现成的方法
(耗时:40ms,内存:15.3M)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
datas = collections.Counter(nums)
for each in datas:
if datas[each] == 1: return each
注意:
1.collections.Counter(nums)输出的是{}字典类型,key为元素,value为元素重复的次数。
2.for each in datas中的each是每个key。
② 切片操作
(耗时:5372ms,内存:15.6M)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums[i] not in nums[0:i] and nums[i] not in nums[i+1:]: return nums[i]
③ 异或
(耗时:48ms,内存:15.3M)
class Solution(object):
def singleNumber(self, nums: List[int]) -> int:
a = 0
for i in nums:
a ^= i
return a
注意:
1.任何数与0异或都是原数。
2.两个相同的数异或是0。
3.对于连个数的异或要转换成二进制来位运算哦!!