The Array ||

来源:互联网 发布:知乎上面的神回复 编辑:程序博客网 时间:2024/05/01 17:41

Merge Sorted Array.

这个题实现并不难,关键是要从后往前扫,才能保证从后往前存入的时候不会把没有扫到的值覆盖掉。

Subsets  这道题本来没啥好说的,recursion想法和 Combination 题目近似,但是在做的时候偶然发现一个问题:在IntelJ里面追踪res的时候,尽管最后结果对,但过程中res变化不正常,

以nums = [1,2]为例, 如果每次加入res时候不传temp对copy而是传本身,在每次迭代中输出res,结果如下:

[[]]
[[1], [1]]
[[1], [1, 2], [1, 2]]
[[2], [1], [1, 2], [2]]
[[], [1], [1, 2], [2]]

可以看出,最后是对的,但过程但记录是不合理但。如何换位传入 remp对copy,整个过程就合理了

[[]]
[[], [1]]
[[], [1], [1, 2]]
[[], [1], [1, 2], [2]]

最后发现是temp在加入res时候没有copy,尽管在同一层最好的变化是被抵消了吧,但是还是不规范,一定要注意recursion中传参问题。另外附加一种iteration的经典思路,code来自Coder_Ganker大神


Unique Paths II :*
这个题思路很好想,但是做了很多遍才做对! 面试中一道题出错三次基本就完了,这道题我错了四五回。。。同样的思路不同的实现角度的复杂度差别很大。我当时做的是in-place的,我用的方法要考虑的edge case不少,很容易出错。下面做法是Coder_Ganker 大神的, 用 O(m)space, 虽然是二维dp的题目,用一维数组来解决大大简化了代码。


Search for a Range : ....

Binary search has always been my weakness. However, consider I just seriously start doing algorithm coding problems, bear with it for now. I should take a big lesson from this one. What is A binary search do? --- it always go to left OR right part in next iteration until two sides finally merge.  Where does binary search end? --- In last iteration, when l == r, you can either change r or change l, which is both correct or harmless. The question is, I should know clearly which one is finally changing and which one remains in right ending position.  In this problem, we do 2 BSs to find right position and left respectively. We want to use ll as l and rr as r, so we modify lr and rl at end of two BSs.


Jump Game : *

Jump Game II : **

Follow up is returning minimum steps needed to reach the last index.  The code is also O(n) solution. 

Coder_Ganker .... 大神就是大神 。。。记住for循环这种用法

 另外还加了一种实现,同样的思路,用的是for + while, 注意for 的用法, 实质是 while + while 


3Sum Closest    : ***
哎 这个题比较绕啊,到了26左右AC的题目,越来越容易出错了。看了思路都不一定很快能做对。这个题说到家还是Binary Search啊。觉得差不多到火候了,Array对题目做到现在四十道左右了,很多Binary Search对题目都不容易一次做对! 这个题目关键是在BS中维护量, 维护最小差,这个差本身可正可负,但是在update的时候,比较的是绝对值。这里有点绕,这跟之前一个题目BS找最小值一个模式,这种不确定搜索,是需要遍历+维护。注意BS结束的点,并不代表最小值或要找的点。





0 0