class Solution:
def canWinNim(self, n: int) -> bool:
if n % 4 !=0:
return True
return False
第303题 区域和检索,数组不可变
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
for i in range(1, len(self.nums)):
self.nums[i] += self.nums[i-1]
def sumRange(self, i: int, j: int) -> int:
return self.nums[j] - self.nums[i-1] if i > 0 else self.nums[j]
第326题 3的幂次
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 3 ** round(math.log(n, 3)) == n
第342题 4的幂次
class Solution:
def isPowerOfFour(self, num: int) -> bool:
return num > 0 and 4 ** round(math.log(num, 4))==num
第344题 反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
第345题 反转字符串中的元音字母
class Solution:
def reverseVowels(self, s: str) -> str:
if len(s) <= 1:
return s
seed = "aeiouAEIOU"
s = list(s)
l = 0
r = len(s)-1
while l < r:
if s[l] not in seed:
l += 1
if s[r] not in seed:
r -= 1
if s[l] in seed and s[r] in seed:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return "".join(s)
第349题 两个数组的交集
暴力求解法
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
for i in range(len(nums1)):
if nums1[i] in nums2 and nums1[i] not in res:
res.append(nums1[i])
return res
用内置set函数
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1)&set(nums2)
第350题 两个数组的交集2
双指针法
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
res = []
i=j=0
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j +=1
elif nums1[i] < nums2[j]:
i +=1
else:
j +=1
return res
第367题 有效的完全平方数
利用牛顿迭代法求解
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1:
return True
r = num
while r*r>num:
r = (r+num/r)//2
if r*r == num:
return True
else:
return False
第371题 两整数之和
class Solution:
def getSum(self, a: int, b: int) -> int:
return sum([a,b])
第374题 猜数字大小
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
l = 1
r = n
while l <= r:
mid = l + (r - l) // 2
flag = guess(mid)
if flag == -1:
r = mid - 1
elif flag == 1:
l = mid + 1
else:
return mid
第387题 字符串中的第一个唯一字符
class Solution:
def firstUniqChar(self, s: str) -> int:
dic = {}
for c in s:
dic[c] = dic[c]+1 if c in dic else 1
unique_chars = [k for k, v in filter(lambda kvp: kvp[1] == 1, dic.items())]
for i, c in enumerate(s):
if c in unique_chars:
return i
return -1
第389题 找不同
s是字母少的,将t中的相同字母替换掉,留下来的就是不同值:
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
for i in s:
t=t.replace(i, "", 1)
return t
求出字符串内所有字符的ASCII码,用t-s得到的ASCII码就是多出来的字母的,ord是获得ASCII码,而chr则相反:
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(sum(map(ord, t))- sum(map(ord, s)))