Binary392IsSubsequence

Greedy

1. Two Pointers & Optimization
2. Recursive

注意循环到本method 是 return methodName(…), 不要忘了return 还是没有理解返回值和循环的作用

_String.substring(startIndex) 如果startIndex = _String.length() , 会返回null 如果> ,则出错

3. HashMap: key is char, value is index

“leeeeetcode”
“yyyyylyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

发生原因是重复的字母都是同样的key, 导致value是最大值, 并不符合情况. 因此单纯的hashmap并不适用题目情况. 需要把value变为index的集合, 所以用List<Integer>因此请看BinarySearch方法1

BinarySearch

1. HashMap and BinarySearch

用hashmap存储相同字母, 例如c在字符串abc里面, c出现的所有位置作为list, list是从小到大的. binarySearch有两个参数, 一个是c 的位置list, 另一个是targetIndex, 这个targetIndex是说list的值必须大于targetIndex (在String t中b字母首次出现的indexh后面) 来确认符合要求的位置. 其中写这个BinarySearch的helper method出现了好多bug.

  • Bug1 分不清list.get(i)和target分别代表什么. i是这个list的index, 而list.get(i)是String t 的index, targetIndex也是String t的位置, 因此进行比较的是这两者, 而非i和targetIndex
  • Bug2 最后的返回值. 我要求找到符合的, 发送String t里面的位置, 作为更新targetIndex的标准, 而未找到则发送-1. 所以首先在BinarySearch里面返回值应该是list.get(i), 而非i
  • Bug3 接上, 其次, 如果在list里面没找到符合target的值 的话, 按照停止条件, 也会停止, 因此i有可能比list.size()大, 这就意味着没找到;
  • Bug4 接上, 有没有必要因为停止值很小, 因此要加一个list.get(i)>= target这个判断条件呢?

附上最终的BinarySearch的代码

     private static int binaryReturnIndex(List<Integer> l, int target) {
        int i = 0, j = l.size() - 1;
        while(i <= j) {
            int mid = (j - i)/2 + i;
            if (target < l.get(mid))
                j = mid - 1;
            else if (target > l.get(mid))
                i = mid + 1;
            else
                return mid;
        }
        if (i < l.size() )
            return l.get(i);
        else
            return -1;
    }

Dynamic Programming

Dynamic programming is when you use past knowledge to make solving a future problem easier.

A good example is solving the fibonacci sequence for n=1,000,002.

This will be a very long process, but what if I give you the results for n=1,000,000 and n=1,000,0001? Suddenly the problem just became more manageable.

Dynamic programming is used a lot in string problems, such as the string edit problem. You solve a subset(s) of the problem and then use that information to solve the more difficult original problem.

With dynamic programming, you store your results in some sort of table generally. When you need the answer to a problem, you reference the table and see if you already know what it is. If not, you use the data in your table to give yourself a stepping stone towards the answer.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值