LeetCode:Contains Duplicate II

来源:互联网 发布:网络女主播六间房 编辑:程序博客网 时间:2024/06/05 10:35

问题描述:

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.

给出一个整数数组,判断该数组内是否有两个元素值是相同的,且他们的索引值相差不大于k,是则返回true,否则返回false

思路:


代码:

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


0 0
原创粉丝点击