Leetcode刷题 2021.03.25
Leetcode1730 获取食物的最短路径
你现在很饿,想要尽快找东西吃。你需要找到最短的路径到达一个食物所在的格子。
给定一个 m x n 的字符矩阵 grid ,包含下列不同类型的格子:
’’ 是你的位置。矩阵中有且只有一个 '’ 格子。
‘#’ 是食物。矩阵中可能存在多个食物。
‘O’ 是空地,你可以穿过这些格子。
‘X’ 是障碍,你不可以穿过这些格子。
返回你到任意食物的最短路径的长度。如果不存在你到任意食物的路径,返回 -1。
两个点或者连通分量之间的最短路径,肯定是BFS了。也是BFS的模板题,就当复习一遍吧。
class Solution {
int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int getFood(char[][] grid) {
//BFS模板
Queue<int[]> queue = new LinkedList<>();
int m = grid.length, n = grid[0].length;
boolean[][] isVisited = new boolean[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (grid[i][j] == '*'){
queue.offer(new int[]{i, j});
isVisited[i][j] = true;
break;
}
}
}
int level = 0;
while (!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
int[] temp = queue.poll();
int x = temp[0], y = temp[1];
// System.out.println(x + " " + y);
if (grid[x][y] == '#') return level;
// grid[x][y] = 'X';
for(int k = 0; k < 4; k++){
int dx = x + directions[k][0], dy = y + directions[k][1];
if (dx >= 0 && dx < m && dy >= 0 && dy < n && grid[dx][dy] != 'X' && !isVisited[dx][dy]){
isVisited[dx][dy] = true;
queue.offer(new int[]{dx, dy});
}
}
}
level++;
}
return -1;
}
}
Leetcode1310 子数组异或查询
有一个正整数数组 arr,现给你一个对应的查询数组 queries,其中 queries[i] = [Li, Ri]。
对于每个查询 i,请你计算从 Li 到 Ri 的 XOR 值(即 arr[Li] xor arr[Li+1] xor … xor arr[Ri])作为本次查询的结果。
并返回一个包含给定查询 queries 所有结果的数组。
对于这类范围查询的题,暴力肯定是超时的。解法也无非就是:前缀和,差分数组(还不会),线段树(还不会。。)等等。所以这题可以考虑异或的性质,不难想到用前缀异或了。
class Solution {
public int[] xorQueries(int[] arr, int[][] queries) {
int n = arr.length;
int[] help = new int[n + 1];
//获取前缀异或数组
for(int i = 1; i < n + 1; i++){
help[i] = help[i - 1] ^ arr[i - 1];
}
//考虑pre[l] ^ pre[r + 1]= (a[0]^ ...a[l - 1])^(a[0] ^ ...a[l - 1] ^ a[l]...a[r]) = a[l] ^ ... ^a[r]
int[] res = new int[queries.length];
for(int i = 0; i < queries.length; i++){
res[i] = help[queries[i][0]] ^ help[queries[i][1] + 1];
}
return res;
}
}
Leetcode676 实现一个魔法字典
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。
这题直接写了个暴力的,击败5%。看了题解大多是用字典树实现的,明天再写吧,回去洗洗睡了。
class MagicDictionary {
Set<String> set;
/** Initialize your data structure here. */
public MagicDictionary() {
set = new HashSet<>();
}
public void buildDict(String[] dictionary) {
for(String dict : dictionary){
set.add(dict);
}
}
public boolean search(String searchWord) {
char[] arr = searchWord.toCharArray();
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < 26; j++){
if (arr[i] - 'a' == j){
continue;
}
char temp = arr[i];
arr[i] = (char) (j + 'a');
if (set.contains(new String(arr))) return true;
arr[i] = temp;
}
}
return false;
}
}