01-数组中重复的数字
哈希表法
思路
- 初始化集合为空集合
- 遍历数组中每一个元素,将元素添加到集合中
- 如果添加成功就继续,否则添加失败说明集合中已经有该元素,那么说明重复了
Java实现
import java.util.*;public class Solution {//hashpublic int duplicate (int[] numbers) {// write code hereSet<Integer> set=new HashSet<>();int res=-1;for(int num:numbers){if(!set.add(num)){res=num;break;}}return res;}}
Python实现
class Solution(object):def findRepeatNumber(self, nums):s=set()for num in nums:if num not in s:s.add(num)else:return numreturn -1
- 时间复杂度:遍历数组O(n),添加到HashSet的时间复杂度O(1)
- 空间复杂度:HashSet占用O(n)的空间复杂度
02-二维数组中查找
原题链接
思路
- 从二维数组的右上角看,可以看到它左侧的元素比它小,右侧的元素比它大
- 因此类似于一棵二叉搜索树,满足左小右大的需求
- 那么我们能否能通过二分的思想将搜索的时间复杂度降到O(logN)呢?
Java实现
