1、丢失的数字
题目描述:https://leetcode.cn/problems/missing-number/
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
ans = n*(n+1)//2
for num in nums:
ans -= num
return ans
2、第一个错误的版本
题目描述:https://leetcode.cn/problems/first-bad-version/
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
class Solution:
def firstBadVersion(self, n: int) -> int:
left,right = 0,n
while(left<=right):
mid = left + (right-left)//2
if(isBadVersion(mid)==False): #如果还未出错
left = mid + 1
if(isBadVersion(mid+1)==True):
return mid+1
elif(isBadVersion(mid)==True): #已经出错
right = mid - 1
if(isBadVersion(mid-1)==False):
return mid
3、移动零
题目描述:https://leetcode.cn/problems/move-zeroes/
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow, fast = 0, 0
while fast < len(nums):
if nums[fast] != 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
fast += 1
return nums
4、单词规律
题目描述:https://leetcode.cn/problems/word-pattern/
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
t = str.split()
if len(pattern) != len(t):
return False
dct = {}
for i in range(len(pattern)):
if pattern[i] not in dct:
if t[i] in dct.values():
return False
dct[pattern[i]] = t[i]
else:
if dct[pattern[i]] != t[i]:
return False
return True
5、Nim游戏
题目描述:https://leetcode.cn/problems/nim-game/
class Solution:
def canWinNim(self, n: int) -> bool:
return bool(n%4)
6、区域和检索
题目描述:https://leetcode.cn/problems/range-sum-query-immutable/
class NumArray:
def __init__(self, nums: List[int]):
self.prefix_sums = [0 for _ in range(len(nums))]
self.prefix_sums[0] = nums[0]
for i in range(1, len(nums)):
self.prefix_sums[i] = self.prefix_sums[i - 1] + nums[i]
def sumRange(self, left: int, right: int) -> int:
start = self.prefix_sums[left - 1] if left > 0 else 0
return self.prefix_sums[right] - start
7、3的幂
题目描述:https://leetcode.cn/problems/power-of-three/
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
elif n == 1:
return True
elif n % 3 != 0:
return False
return self.isPowerOfThree(n//3)