219. Contains Duplicate II

原题链接:https://leetcode.com/problems/contains-duplicate-ii/description/
又是一道不错的题目:

import java.util.HashMap;
import java.util.Map;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.containsNearbyDuplicate(new int[]{1, 2, 3, 5, 8, 7 ,2, 6}, 5));
    }

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>(nums.length);

        for (int i = 0; i < nums.length; i++) {
            if (map.keySet().contains(nums[i])) {
                int oldIndex = map.get(nums[i]);
                if (i - oldIndex <= k) {
                    return true;
                }
            }
            map.put(nums[i], i);
        }

        return false;
    }
}
posted @ 2018-03-23 11:08  optor  阅读(82)  评论(0编辑  收藏  举报