leetcode|Single Number(136)
2015-12-05 22:37
429 查看
Given an 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?
way1:使用字典结构,记录每个单词出现的次数
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
for item in nums:
if item not in count:
count.setdefault(item,0)
count[item] += 1
for item in count:
if count[item] == 1:
return item
way2:使用异或逻辑特点,相同为0,相异为1。这个序列的数据有个特点,除了其中的一个只出现一次外,其它的数据都出现两次,所以当把这个序列的所有数据进行异或,就可以得到只出现一次那个数了。当然,这里面也很巧妙的使用了匿名函数lamda(我目前觉得该函数最大的好处就是不需要命函数名~)和函数式编程中的reduce
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x ^ y, nums)
参考资料: http://jeffxie.blog.51cto.com/1365360/328207 python内置函数map/reduce/filter
http://www.runoob.com/python/python-operators.html#ysf2 python运算符
http://woodpecker.org.cn/diveintopython/power_of_introspection/lambda_functions.html 使用lambda函数
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
way1:使用字典结构,记录每个单词出现的次数
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
for item in nums:
if item not in count:
count.setdefault(item,0)
count[item] += 1
for item in count:
if count[item] == 1:
return item
way2:使用异或逻辑特点,相同为0,相异为1。这个序列的数据有个特点,除了其中的一个只出现一次外,其它的数据都出现两次,所以当把这个序列的所有数据进行异或,就可以得到只出现一次那个数了。当然,这里面也很巧妙的使用了匿名函数lamda(我目前觉得该函数最大的好处就是不需要命函数名~)和函数式编程中的reduce
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x ^ y, nums)
参考资料: http://jeffxie.blog.51cto.com/1365360/328207 python内置函数map/reduce/filter
http://www.runoob.com/python/python-operators.html#ysf2 python运算符
http://woodpecker.org.cn/diveintopython/power_of_introspection/lambda_functions.html 使用lambda函数
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解