简单部分
数组中重复的数字: hash表、数组遍历
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例:
输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3
PS: 2 <= n <= 100000
一刷:
遍历数组再用hash表存放:
class Solution:def findRepeatNumber(self, nums: List[int]) -> int:numberset = dict()for i in nums:if i in numberset:return ielse:numberset[i] = 1return -1
二维数组中的查找: hash表、数组遍历
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
PS:
限制:0 <= n <= 1000,0 <= m <= 1000
一刷:
从左到右递增,从上到下递增, 那么从最右上角开始查找就像是一棵二分查找树
class Solution:def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:if matrix == []:return Falsei = 0j = len(matrix[0]) - 1while((j >= 0) and ( i <= len(matrix) - 1)):print(i)if matrix[i][j] == target:return Trueelif matrix[i][j] < target:i += 1elif matrix[i][j] > target:j -= 1return False
时间复杂度O(n+m)