Contains Duplicate II

来源:互联网 发布:怎么查看电脑ip端口 编辑:程序博客网 时间:2024/06/10 21:38

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

题目大意是:在一个数组中是否存在nums[i]==nums[j](假设i<j),且j-i<=k

思路和以前有个题目类似,借助HashMap来保存nums[i]和i,这样后面判断是否重复出现的只需查找map即可。如果重复出现,那就查键对应的值之差是否小于等于k

代码如下:

public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++){            if(map.containsKey(nums[i])){                int j = map.get(nums[i]);                if(i-j<=k){                    return true;                }else{                    //i-j>k                    //移除之前的,接着执行13行代码,把第二次重复出现的数的位置保存map中                    //作为新的键值对                    map.remove(nums[i]);                }            }              map.put(nums[i],i);        }             return false;    }}


                                             
0 0
原创粉丝点击