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

LeetCode -- Contains Duplicate II

时间:2015-09-18 21:59:19      阅读:312      评论: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.

 

Analysis:

给出一个整数数组和一个整数K,找出在K的范围内是否有重复数字。

思路一:刚开始是想用一个滑动窗口,然后在每段窗口内用一个HashMap来判断是否有重复数字,但是后面发现越想情况越多,无法用一个通用的coding解决问题,因此换了一种思路。

思路二:只遍历数组一遍,用HashMap保存key为数组数据,value保存数组下标,当map中出现相同的数字时判断下标范围是否在k之内。

 

Answer:

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

 

LeetCode -- Contains Duplicate II

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4820283.html

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