fvdcx's blog


  • 首页

  • 分类

  • 关于

  • 归档

  • 标签

leetcode-gas-station

发表于 2016-12-25   |   分类于 算法 , leetcode   |  

题目大意

  https://leetcode.com/problems/gas-station/

  一个环形有n个加油站,每个加油站能为汽车加油量不同,汽车在两站之间耗费油量也不同,假定汽车油桶足够大,问从哪个加油站出发,能不缺油地绕一个环形,如果不存在则返回-1

题目分析

  暴力解法是O(n^2),看了下disscuss区的解法https://discuss.leetcode.com/topic/39755/proof-of-if-total-gas-is-greater-than-total-cost-there-is-a-solution-c/2 主要是证明了两点:

  1. 如果sum(gas) >= sum(cost),那么一定存在方案
  2. 在假定存在方案的前提下,算法不妨从0开始到n-1遍历,最小的累积sum(gas) - sum(cost)的位置为loc,那么loc+1即为出发点

  这两点的证明在原帖中有很详细的解释。我觉得这种trick题真的是不看巧妙解法,自己很难想出来。

阅读全文 »

leetcode-implement-trie-prefix-tree

发表于 2016-12-25   |   分类于 算法 , leetcode   |  

题目大意

  https://leetcode.com/problems/implement-trie-prefix-tree/

  实现字典树

题目分析

  细节实现题,只要理解好trie树概念,自己定义好数据及结构。我这里trie树的节点保存了26个子节点,节点字符,以及词频freq,之所以没有存“是否为叶子节点”的变量,是因为词频能够保留更多的信息。

阅读全文 »

leetcode-word-search

发表于 2016-12-25   |   分类于 算法 , leetcode   |  

题目大意

  https://leetcode.com/problems/word-search/

  在一个字母的矩阵中搜索一个单词是否存在

题目分析

  典型的DFS题目,但要注意不要使用辅助标记数组的方式,很容易超时,每次访问过的点用一个非字母的字符标记一下就可以了

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
private int row;
private int col;
private int len;
private boolean check(char[][] board, int si, int sj) {
return (si >=0 && si < row && sj >=0 && sj < col);
}
private boolean search(char[][] board, int si, int sj, int idx, String word) {
if (idx > len - 1) {
return true;
}
if (!check(board, si, sj) || word.charAt(idx) != board[si][sj] || board[si][sj] == '.') {
return false;
}
char pre = board[si][sj];
board[si][sj] = '.'; // 用一个非字母的字符标记
if(search(board, si - 1, sj, idx + 1, word) || search(board, si + 1, sj, idx + 1, word) || search(board, si, sj - 1, idx + 1, word) || search(board, si, sj + 1, idx + 1, word)) { // 四个方向搜索
return true;
}
board[si][sj] = pre;
return false;
}
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0) {
return false;
}
row = board.length;
col = board[0].length;
len = word.length();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (search(board, i, j, 0, word)) {
return true;
}
}
}
return false;
}
}

leetcode-word-ladder-ii

发表于 2016-12-21   |   分类于 算法 , leetcode   |  

题目大意

  https://leetcode.com/problems/word-ladder-ii

  接着上一篇博客的问题

题目分析

  word-ladder-ii要求输出全部路径,要点如下:

  1. 主体思想还是BFS,但是要遍历到所有的最短路径情况,因此除了借助队列,还要存访问过的路径,也就是一张隐式图
  2. 对于标记数组的处理也有所不同,访问过一个字符串以后,不能直接标记为已访问,要等同层其它字符串也访问完以后,统一将这一层的字符串标记为已访问,否则上一层的其他尚未访问过的字符串再也访问不了这些字符串了。
  3. 在将字符串加入队列时,如果已经在同层访问过了,不要再加入队列,否则会重复。
  4. 最后对于记录的隐式图进行DFS
阅读全文 »
1…181920…38
fvdcx

fvdcx

149 日志
14 分类
20 标签
GitHub
© 2015 - 2017 fvdcx
由 Hexo 强力驱动
主题 - NexT.Pisces