1、相交链表
题目描述:https://leetcode.cn/problems/intersection-of-two-linked-lists/
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A
2、Excel表列名称
题目描述:https://leetcode.cn/problems/excel-sheet-column-title/
class Solution:
def convertToTitle(self, n: int) -> str:
t = n
s = ''
while t > 0: # 每次循环 是 每次取模得到数字 的过程
t -= 1 # 把 从1开始满27进位 变回 从0开始满26进位
a, b = t//26, t%26 # 这里b的取值范围是0-25
s = s + chr(b+65) # A的ASCII码是65,b+65表示 0-25 和 A-Z 有了一一对应
t = a
return s[::-1] # 最后将 优先获得的低位数字 反转到最后
3、多数元素
题目描述:https://leetcode.cn/problems/majority-element/
class Solution:
def majorityElement(self, nums: List[int]) -> int:
ans = -1
cnt = 0
for num in nums:
if not cnt:
ans = num
cnt = 1
else:
if num == ans:
cnt += 1
else:
cnt -= 1
return ans
4、Excel表列序号
题目描述:https://leetcode.cn/problems/excel-sheet-column-number/
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
res = 0
for c in columnTitle:
cur = ord(c) - ord('A') + 1
res = res * 26 + cur
return res
5、颠倒的二进制位
题目描述:https://leetcode.cn/problems/reverse-bits/
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for i in range(32):
res = (res << 1) + (n & 1)
n >>= 1
return res
6、位1的个数
题目描述:https://leetcode.cn/problems/number-of-1-bits/
class Solution:
def hammingWeight(self, n: int) -> int:
n = bin(n)
sc = str(n)[2:]
frequency = collections.Counter(sc)
return frequency['1']
7、快乐数
题目描述:https://leetcode.cn/problems/happy-number/
class Solution:
def isHappy(self, n: int) -> bool:
pre = set([n])
def check(num):
lst = [int(va)**2 for va in str(num)]
return sum(lst)
while n!=1:
n = check(n)
if n in pre:
return False
pre.add(n)
return True