1兩數之和(近半年內,字節跳動在面試中考查此題達到 152 次)
class Solution(object):
def twoSum(self, nums, target):
dic = {}
for i,num in enumerate(nums):
if num in dic:return [dic[num],i]
else:dic[target - num] = i
11盛最多水的容器(騰訊、百度、字節跳動在近半年內面試常考)
class Solution:
def maxArea(self, height: List[int]) -> int:
max_ , l ,r = 0, 0 , len(height) -1
while l < r:
if l > 0 and height[l+1] < height[l]:continue
if r > 1 and height[r - 1] < height[r]:continue
h = min(height[r] , height[l])
max_,l,r = max(max_,h * (r - l)),l + (height[l] == h),r -(height[r] == h)
return max_
283移動零(華爲、字節跳動在近半年內面試常考)
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = 0
for j in range(len(nums)):
if nums[j]:
nums[i], nums[j] = nums[j], nums[i]
i += 1
70 爬樓梯(阿里巴巴、騰訊、字節跳動在半年內面試常考)
class Solution:
def climbStairs(self, n: int) -> int:
# if n < 3:return n
# first, second = 1,2
# for _ in range(3,n + 1):
# first, second = second,first + second
# return second
sqrt5 = sqrt(5)
fibn = pow((1 + sqrt5)/2,n + 1) - pow((1 - sqrt5)/ 2, n + 1)
return int(fibn/sqrt5)
數學法的證明如下:
補充同類練習:
509. 斐波那契數
# 數學的方法
class Solution:
def fib(self, N: int) -> int:
sqrt5 = sqrt(5)
fib = pow((1 + sqrt5)/2, N) - pow((1 - sqrt5)/2,N)
return int(fib/sqrt5)
15 三數之和(國內、國際大廠歷年面試高頻老題)
面試的時候和麪試官說解法,分析代碼的時間複雜度,並且把解法3 的代碼寫出來
解法1:暴力法 O(N^3)
解法2:排序 + HashO(N^2)
解法3雙指針 / 夾逼法 O(N)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
length = len(nums)
for i in range(length - 2):
if nums[i] > 0:break
if i > 0 and nums[i] == nums[i-1]:continue
l, r = i + 1,length - 1
while l < r:
total = nums[i] + nums[l] + nums[r]
if total < 0: l += 1
elif total > 0: r -= 1
else:
res.append([nums[i],nums[l],nums[r]])
while l < r and nums[l] == nums[l+1]:l += 1
while l < r and nums[r] == nums[r-1]:r -= 1
l += 1
r -= 1
return res