LeetCode 137 [Single Number II]
原題
給出3*n + 1 個的數字,除其中一個數字之外其他每個數字均出現三次,找到這個數字。
樣例
給出** [1,1,2,3,3,3,2,2,4,1]** ,返回 4
解題思路
- 方法一:三進位制不進位加法,比如02 + 01 = 00 (2+1=3做加法不進位)。所以同一個數,比如7的三進製表示為21,21+21+21 = 00 即十進位制下的0。最終程式碼即統計每一位上1,對3取模
- 方法二:分別統計,記錄出現一次,兩次,三次的數
完整程式碼
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones, twos, threes = 0, 0, 0
for item in A:
twos |= ones & item
ones ^= item
threes = ones & twos
ones ^= threes
twos ^= threes
return ones
相關文章
- Leetcode 137. Single Number IILeetCode
- 137-Single Number II
- [LeetCode] 305. Number of Islands IILeetCode
- Leetcode 之 PHP 解析 (260. Single Number III)LeetCodePHP
- 136. Single Number
- 260-Single Number III
- Leetcode 137:只出現一次的數字 II(最詳細的解法!!!)LeetCode
- Leetcode Number of islandsLeetCode
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- Leetcode 933 Number of Recent CallsLeetCode
- [LeetCode] 9. Palindrome NumberLeetCode
- LeetCode之Fibonacci Number(Kotlin)LeetCodeKotlin
- leetcode-90. Subsets IILeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode 1103[分糖果II]LeetCode
- Leetcode 611 javascript Valid Triangle NumberLeetCodeJavaScript
- LeetCode之Number of Recent Calls(Kotlin)LeetCodeKotlin
- [LeetCode] 248. Strobogrammatic Number IIILeetCode
- [LeetCode] 191. Number of 1 BitsLeetCode
- Leetcode 17 Letter Combinations of a Phone NumberLeetCode
- 【Leetcode】1395. Count Number of TeamsLeetCode
- [LeetCode] 210. Course Schedule IILeetCode
- [LeetCode] 212. Word Search IILeetCode
- [Leetcode]253. Meeting Rooms IILeetCodeOOM
- [LeetCode] 2105. Watering Plants IILeetCode
- LeetCode 52. N皇后 IILeetCode
- [leetcode]linked-list-cycle-iiLeetCode
- leetcode 219. Contains Duplicate IILeetCodeAI
- [LeetCode] 910. Smallest Range IILeetCode
- [LeetCode] 45. Jump Game IILeetCodeGAM
- LeetCode-047-全排列 IILeetCode
- [LeetCode] 3152. Special Array IILeetCode
- LeetCode Palindrome Number(009)解法總結LeetCode
- Leetcode – 017. Letter Combinations of a Phone NumberLeetCode
- [LeetCode] 3238. Find the Number of Winning PlayersLeetCode