码迷,mamicode.com
首页 > 其他好文 > 详细

Contains Duplicate II 解答

时间:2015-09-12 00:49:55      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

Question

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.

Solution -- HashMap

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         int length = nums.length;
 4         if (length <= 1 || k < 1)
 5             return false;
 6         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 7         int min = Integer.MAX_VALUE;
 8         for (int i = 0; i < length; i++) {
 9             if (map.containsKey(nums[i])) {
10                 int prev = map.get(nums[i]);
11                 int gap = i - prev;
12                 min = Math.min(min, gap);
13             }
14             map.put(nums[i], i);
15         }
16         if (min <= k)
17             return true;
18         else
19             return false;
20     }
21 }

 

Contains Duplicate II 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4802343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!