“这些事儿在熟练之后,也许就像喝口水一样平淡,但却能给初学者带来巨大的快乐,我一直觉得,能否始终保持如初学者般的热情、专注,决定了在做某件事时能走多远,能做多好。” 该系列文章由python编写,遵循LeetBook 列表/腾讯的刷题顺序,所有代码已通过。每日3道,随缘剖析,希望风雨无阻,作为勉励自己坚持刷题的记录。
哈哈哈今天正好刷到这个专题的最后两道凑不起了,偷个懒啦,就写两道。
- 二刷啦(详细的解释在这篇文章里的第49题),分治法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
def majority_element_rec(lo, hi) -> int:
if lo == hi:
return nums[lo]
mid = (hi - lo) // 2 + lo
left = majority_element_rec(lo, mid)
right = majority_element_rec(mid + 1, hi)
if left == right:
return left
left_count = sum(1 for i in range(lo, hi + 1) if nums[i] == left)
right_count = sum(1 for i in range(lo, hi + 1) if nums[i] == right)
return left if left_count > right_count else right
return majority_element_rec(0, len(nums) - 1)
- 投票法,现在看还是感觉很奇妙!
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
231. 2 的幂
- 位运算1:若满足是2的幂,则一定有n&(n-1) ==0,因为n满足100…000,n-1满足011…111。把n=0的特殊情况注意一下即可。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n != 0 and n & (n - 1) == 0
- 取余判断(简单题好让人开心)
class Solution:
BIG = 2**30
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and Solution.BIG % n == 0



