fvdcx's blog


  • 首页

  • 分类

  • 关于

  • 归档

  • 标签

lintcode-fast-power

发表于 2017-10-11   |   分类于 算法 , lintcode   |  

题目大意

  http://www.lintcode.com/zh-cn/problem/fast-power

  快速幂运算

题目分析

  快速幂,将n转化成二进制逐位累乘

阅读全文 »

leetcode-non-decreasing-array

发表于 2017-10-11   |  

题目大意

  https://leetcode.com/problems/non-decreasing-array/

  数组中至多修改一个元素的值,问能不能变成非递减数组

题目分析

  思路参考了 https://discuss.leetcode.com/topic/101144/java-c-simple-greedy-like-solution-with-explanation

  有点贪心的思路,每次遇到i,可以判断i是否比i+1处的值大,如果大说明违反了“非递减”,cnt加1,同时需要修改值,使得nums[i]和nums[i+1]变成相同值,至于变成谁的值,还需进一步比较num[i-1]和nums[i+1],具体边界控制可以看下代码。

阅读全文 »

leetcode-maximum-width-of-binary-tree

发表于 2017-08-20   |   分类于 leetcode , 算法   |  

题目大意

  https://leetcode.com/contest/leetcode-weekly-contest-46/problems/maximum-width-of-binary-tree/

  求树的同层横向最大距离。

题目分析

  思路参考了 https://discuss.leetcode.com/topic/100149/c-java-clean-code-with-explanation

  利用DFS计算,要为每个节点引入id(类似于二叉树用数组存储的思路,id的节点左右子节点存放在2 * id和2 * id + 1位置),方便后续计算距离。

代码

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int ans;
private void dfs(TreeNode cur, int level, int idx, List<Integer> leftIds) {
if (cur == null) {
return;
}
if (leftIds.size() == level) {
leftIds.add(idx);
}
ans = Math.max(ans, idx - leftIds.get(level) + 1);
dfs(cur.left, level + 1, idx * 2, leftIds);
dfs(cur.right, level + 1, idx * 2 + 1, leftIds);
}
public int widthOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
ans = 1;
List<Integer> leftIds = new ArrayList<>();
dfs(root, 0, 1, leftIds);
return ans;
}
}

  时间复杂度:O(n),空间复杂度:o(h)

leetcode-decode-ways-ii

发表于 2017-07-11   |   分类于 算法 , leetcode   |  

题目大意

  https://leetcode.com/problems/decode-ways-ii/#/description

  Decode Ways 的加强版,增加了*,*能匹配1-9(注意不能匹配0),题目输入保证只含有*,`0-9。并对输出取模。

题目分析

  跟Decode Ways一样,很容易看出来是DP,可以把*的情况分解成9种,然后用二维数组的第二维度代表1-9这9种情况,实际转移方程就是分情况讨论稍微麻烦了一点,具体可以看下代码。

阅读全文 »
12…38
fvdcx

fvdcx

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