Easy-题目41:219. Contains Duplicate II
2016-05-30 20:30
393 查看
题目原文:
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)
成绩:
16ms,beats 5.31%,众数14ms,30.23%
cmershen的碎碎念:
使用了trivial的解法因此成绩低于平均值(但不算太差),可能是HashMap浪费了开销,discuss中似乎有基于快排的解法,有待日后研读。
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中似乎有基于快排的解法,有待日后研读。
相关文章推荐
- Easy-题目32:172. Factorial Trailing Zeroes
- Only Link: Inheritance and the prototype chain
- Easy-题目18:70. Climbing Stairs
- Easy-题目10:217. Contains Duplicate
- ping www.baidu.com 不通 开启DNS
- xenomai-GNU/Linux上的RTOS模拟架构实现
- Make things beautiful again !
- Make things beautiful again !
- Make things beautiful again !
- Make things beautiful again !
- codeforces 667A A. Pouring Rain(水题)
- http://www.mamicode.com/info-detail-1150460.html
- IntelliJ IDEA 15.0.2运行grails工程不能自动重新加载修改后的类的问题
- 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/46596109;
- rails入门
- PAT 1014 Waiting in Line (模拟)
- PAT 1014 Waiting in Line (模拟)
- hdu-1789 :Doing Homework again
- /var/spool/postfix/maildrop/ 中有大量的文件
- strong,weak,retain,assign,copy nomatic 等的区别