首页 > 学院 > 开发设计 > 正文

[LeetCode] Contains Duplicate II

2019-11-15 01:10:30
字体:
来源:转载
供稿:网友
[LeetCode] Contains Duplicate II

Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such thatnums[i] = nums[j]and the difference betweeniandjis at mostk.

这道题还是很简单的。没啥可说的。直接用hashmap就可以做了,借助containsKey(),get()还有put()。

代码如下。~

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表