Leetcode - Contains Duplicate II

《Leetcode - Contains Duplicate II》 Paste_Image.png

My code:

import java.util.HashMap;

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0)
            return false;
        HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (!h.containsKey(nums[i]))
                h.put(nums[i], i);
            else {
                int idBefore = h.get(nums[i]);
                if (i - idBefore <= k)
                    return true;
                else {
                    h.put(nums[i], i);
                }
            }
        }
        return false;
    }
}

My test result:

《Leetcode - Contains Duplicate II》 Paste_Image.png

这次作业也不是很难,主要意思理解的不太对。
他的意思是,能不能找到两个相等的数,他们的index只差最大不能超过k,即,不一定要等于k。然后就顺理成章了。

**
总结: Array
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length < 2)
            return false;
        HashMap<Integer, Integer> tracker = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (tracker.containsKey(nums[i])) {
                int index = tracker.get(nums[i]);
                if (Math.abs(index - i) <= k)
                    return true;
                tracker.put(nums[i], i);
            }
            else
                tracker.put(nums[i], i);
        }
        return false;
    }
}

我觉得还是利用了 Two Sum 的思想。
就是把我所需要的那个值(相等)塞入HashMap中。
key : needed value –> value: index of this value
然后,
后面如果当前访问值不在HashMap中,就继续更新该HashMap
如果在,那么取出index,比较下是不是在K以内。
如果在,return true at once.
如果不在, 更新HashMap, 同样的value对应了当前的index。这样,后续如果还有相同value的index,如果和该最新版的index距离超过K,就一定与之前的超过K。
就是这么个思路。
2Sum 的思想还是很普遍的。

Anyway, Good luck, Richardo!

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/78d29d5a094b#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞