看板 Python 關於我們 聯絡資訊
第一次發文 如果有那裡不妥當請告知 最近在LEETCODE刷提 遇到一題求 list 裡面任意兩數字XOR最大值 題目連結在這邊 https://goo.gl/HPH4Sm 這題最快的解答是 class Solution: def findMaximumXOR(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 for bit in range(31, -1, -1) : ans = (ans << 1) + 1 pre = set() for n in nums : p = (n >> bit) & ans if p in pre : #1 break #2 pre.add(ans - p) #3 else : #4 ans -= 1 return ans 我的問題在我標#1-4的地方 我不太明白這邊的if else statement 怎麼運作的(特別是#4) 一開始我以為是當if p not in pre: 就會直接跳到#4 但是好像不太對 請問有人可以跟我說明一下嗎? 非常感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 174.55.55.170 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1530067068.A.3E3.html
djshen: else是跟著for的 06/27 11:20
jlhc: for正常結束後會做else的內容 06/28 01:17
windclara: FOR-ELSE,好像是Python特有的 @@ 06/28 11:14
cphe: else是跟著for,看縮排比較好懂~ for完整跑完就會執行else 06/28 14:10
cphe: 通常是用來判斷是否有中離(? 06/28 14:10
cphe: 這題不暴力解就是利用xor的特性,a^b=c則 a^c=b,c是預期最 06/28 14:12
cphe: 大值,再判斷做完xor後b是否在set裡面,沒有該bit設為零 06/28 14:13
cphe: 簡單來說就是每個bit掃一次,由高位元到低位元跑32次 06/28 14:13
cphe: 你問的 else: ans -= 1就代表不在set中,要把前面加1減回來 06/28 14:14
benchen0812: 感謝說明!! 06/28 23:16