力扣做题笔记
一、Easy
240. 搜索二维矩阵2
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。 每列的元素从上到下升序排列。
朴素的想法是二分查找
但是最好的方式是Z字型查找,从矩阵的右上角开始遍历,向左是变小,向下是变大。
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
x = 0
y = len(matrix[0]) - 1
n = y
m = len(matrix) - 1
while x<=m and y >=0:
if matrix[x][y] == target:
return True
elif matrix[x][y] < target:
x = x+1
continue
else:
y = y-1
continue
return False
15. 三数之和
O(n*n)的时间复杂度
首先排序,先固定第一个数,然后在第一个数后面的区间内,双指针向内并拢。
target = -a
如果b+c > target,right–,
如果b+c<target,left++
b+c == target, 就存入ans中
left==right的时候跳出
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
ans = list()
# 枚举 a
for first in range(n):
# 需要和上一次枚举的数不相同
if first > 0 and nums[first] == nums[first - 1]:
continue
# c 对应的指针初始指向数组的最右端
third = n - 1
target = -nums[first]
# 枚举 b
for second in range(first + 1, n):
# 需要和上一次枚举的数不相同
if second > first + 1 and nums[second] == nums[second - 1]:
continue
# 需要保证 b 的指针在 c 的指针的左侧
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加
# 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans
215. 数组中的第K个最大元素(百度二面)
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
- 冒泡排序方式
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
for j in range(k):
for i in range(n-2, -1 + j, -1):
if nums[i+1]>nums[i]:
nums[i+1], nums[i] = nums[i], nums[i+1]
return nums[k-1]
- 快排方式
def quickSort(left, right, k):
if left >= right:
return
flag = nums[left]
l = left
r = right
while l < r:
while l < r and nums[r] < flag:
r -= 1
while l < r and nums[l] >= flag:
l += 1
nums[l], nums[r] = nums[r], nums[l]
nums[l], nums[left] = nums[left], nums[l]
if l == k:
return
elif l < k:
quickSort(l+1, right, k)
else:
quickSort(left, l-1, k)
n = len(nums)
quickSort(0, n-1, k-1)
print(nums)
return (min(nums[:k]))
- 最大堆方式
堆建立的过程中,将倒数第二层的节点开始进行下沉操作,也就是如果两个子节点有比该节点大的,选取最大的交换
移除堆顶元素的过程就是,把堆顶元素放到最后,然后开始自上而下的下沉
添加元素的时候,先放到末尾,然后不断进行上移操作
"""
最大堆
"""
```python
class MaxHeap(object):
# def __init__(self):
# self.data = [] # 创建堆
# self.count = len(self.data) # 元素数量
def __init__(self, arr):
self.data = copy.copy(arr)
self.count = len(self.data)
i = self.count / 2
while i >= 1:
self.shiftDown(i)
i -= 1
def size(self):
return self.count
def isEmpty(self):
return self.count == 0
def insert(self, item):
# 插入元素入堆
self.data.append(item)
self.count += 1
self.shiftup(self.count)
def shiftup(self, count):
# 将插入的元素放到合适位置,保持最大堆
while count > 1 and self.data[(count/2)-1] < self.data[count-1]:
self.data[(count/2)-1], self.data[count-1] = self.data[count-1], self.data[(count/2)-1]
count /= 2
def extractMax(self):
# 出堆
if self.count > 0:
ret = self.data[0]
self.data[0], self.data[self.count-1] = self.data[self.count-1], self.data[0]
self.data.pop()
self.count -= 1
self.shiftDown(1)
return ret
def shif