[Leetcode] 136. Single Number
5295 ワード
問題のショートカット
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(n)O(n)O(n)
2∗(a+b+c)−(a+a+b+b+c)=c2*(a+b+c)-(a+a+b+b+c) = c2∗(a+b+c)−(a+a+b+b+c)=c
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(n)O(n)O(n)
a ⊕ 0 = a
a ⊕ a = 0
a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b
cf)XOR演算は結合・交換法則を成立する.
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(1)O(1)O(1)
Hash Table
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(n)O(n)O(n)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hashtable = dict()
for num in nums:
if num in hashtable:
del hashtable[num]
else:
hashtable[num] = 1
return list(hashtable.keys())[0]
Math
2∗(a+b+c)−(a+a+b+b+c)=c2*(a+b+c)-(a+a+b+b+c) = c2∗(a+b+c)−(a+a+b+b+c)=c
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(n)O(n)O(n)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
deduplicated = list(set(nums))
timedSum = 0
for num in deduplicated:
timedSum += 2* num
for num in nums:
timedSum -= num
return timedSum
Bit Manipulation
a ⊕ 0 = a
a ⊕ a = 0
a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b
cf)XOR演算は結合・交換法則を成立する.
Time Complexity: O(n)O(n)O(n)
Space Complexity: O(1)O(1)O(1)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for num in nums:
res ^= num
return res
Reference
この問題について([Leetcode] 136. Single Number), 我々は、より多くの情報をここで見つけました https://velog.io/@haebin/Leetcode-136.-Single-Numberテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol