Easy-题目41:219. Contains Duplicate II

原创 2016年05月30日 20:30:15

题目原文:
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 jis at most k.
题目大意:
给一个数组nums和整数K,问是否存在两个下标i和j,使得nums[i]=nums[j],并且|i-j|≤k。
题目分析:
使用HashMap记录一组key-value对,其中key为数组中元素的值,value为所在下标。
当key不重复时加入HashMap即可,如果发现了重复的key,则判断当前数组下标和value值(分别对应题干中的i和j)绝对值是否≤k。
源码:(language:java)

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]) && Math.abs(i-map.get(nums[i]))<=k)
                return true;
            else
                map.put(nums[i],i);
        }
        return false;
    }
}

成绩:
16ms,beats 5.31%,众数14ms,30.23%
cmershen的碎碎念:
使用了trivial的解法因此成绩低于平均值(但不算太差),可能是HashMap浪费了开销,discuss中似乎有基于快排的解法,有待日后研读。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

219. Contains Duplicate II [easy] (Python)

题目链接https://leetcode.com/problems/contains-duplicate-ii/题目原文 Given an array of integers and an int...

217, 219,220. Contains Duplicate I, II, III

Given an array of integers, find if the array contains any duplicates. Your function should return ...

leetcode: (219) Contains Duplicate II

【Question】 Given an array of integers and an integer k, find out whether there are two distinct ind...
  • zk031
  • zk031
  • 2015年08月28日 20:50
  • 178

【leetcode】219. Contains Duplicate II

一、题目描述 Given an array of integers and an integer k, find out whether there are two distinct indic...

LeetCode笔记:219. Contains Duplicate II

判断一个数组中一定范围内是否有相同的数字

219. Contains Duplicate II---数组中两个重复的数字的下标最多相差k

Given an array of integers and an integer k, find out whether there are two distinct indices i and j...

219. Contains Duplicate II

这道题目类似上道题目217,考查的主要是hash表的用法。 描述: Given an array of integers and an integer k, find out whether th...

Leetcode 219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j...

[leetcode]: 219. Contains Duplicate II

1.题目Given an array of integers and an integer k, find out whether there are two distinct indices i a...

#219 Contains Duplicate II

题目: Given an array of integers and an integer k, find out whether there there are two distinct in...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Easy-题目41:219. Contains Duplicate II
举报原因:
原因补充:

(最多只允许输入30个字)