219Contains Duplicate II

来源:互联网 发布:手机语音拨号软件 编辑:程序博客网 时间:2024/06/04 19:02

题目链接:https://leetcode.com/problems/contains-duplicate-ii/

题目:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

解题思路:

  1. 数据结构 HashMap, key 为元素值,value 为该元素的数组下标。
  2. 如果哈希表中没有该元素,就把元素及其下标 put 到哈希表中。
  3. 如果哈希表中已有该元素,获得 HashMap 中该元素之前的下标,如果当前下标与哈希表中的下标的差 小于等于 k,返回 true。否则,将当前下标放入 map 中,替换之前的下标。
public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        if(nums == null || nums.length == 0)            return false;        HashMap<Integer, Integer> map = new HashMap();        int len = nums.length;        for(int i = 0; i < len; i ++) {            if(map.containsKey(nums[i])) {                int pre = map.get(nums[i]);                if(i - pre <= k)                    return true;                else                    map.put(nums[i], i);            } else                map.put(nums[i], i);        }        return false;    }}
19 / 19 test cases passed.Status: AcceptedRuntime: 452 ms
0 0
原创粉丝点击