博主个人博客网站:文客
这个系列主要记录在力扣刷题的总结和问题
如果你想每天和我一起刷题,可以关注一下我的个人博客网站:文客,我会每天在这里更新技术文章和面试题,也会及时收到大家的评论与留言,欢迎各位大佬来交流!
79. 单词搜索
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
思路:
深度优先搜索,从每个点开始搜索,如果找到单词,返回true
题解:
class Solution {
public boolean exist(char[][] board, String word) {
boolean[][] visited = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(dfs(board,word,visited,i,j,0) == true){
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board, String word, boolean[][] visited, int i, int j,int index){
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] == true
|| word.charAt(index) != board[i][j]){
return false;
}
if(index == word.length() - 1){
return true;
}
visited[i][j] = true;
boolean ans = dfs(board,word,visited,i - 1,j,index + 1) ||
dfs(board,word,visited,i + 1,j,index + 1) ||
dfs(board,word,visited,i,j - 1,index + 1) ||
dfs(board,word,visited,i,j + 1,index + 1);
visited[i][j] = false;
return ans;
}
}
128. 最长连续序列
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n)
的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
思路:
用哈希表存储数组中的元素,提高搜索效率,同时还可以去重。
遍历哈希表,if(!set.contains(i - 1))
,这句代码用于判断当前数字是否是一段连续序列的开头,如果集合中有2和3,那么3就不是一个连续序列的开头,计算它的最长连续序列没有意义。
当找到一个连续序列的开头时,依次判断比他大1的元素是否在哈希表中,并计算长度。
题解:
class Solution {
public int longestConsecutive(int[] nums) {
int res = 0;
Set<Integer> set = new HashSet<>();
for(int i : nums){
set.add(i);
}
for(int i : set){
if(!set.contains(i - 1)){
int t = 1;
int num = i;
while(set.contains(num + 1)){
t++;
num++;
}
res = Math.max(res,t);
}
}
return res;
}
}