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

leetCode-Contains Duplicate II

时间:2017-11-26 21:03:03      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:包含   color   nta   list   ecs   ica   set   whether   shm   

Decsription:
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 absolute difference between i and j is at most k.

My Solution:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,List> indexMap = new<Integer,List> HashMap();
        int len = nums.length;
        for(int i = 0;i < len;i++){
            List<Integer> list;
            if(indexMap.get(nums[i]) == null){
                list = new ArrayList<Integer>();
                list.add(i);
                indexMap.put(nums[i],list);
            }else{
                list = (ArrayList<Integer>)indexMap.get(nums[i]);
                list.add(i);
            }
            if(list.size() >= 2){
                if(list.get(list.size() - 1) - list.get(list.size() - 2) <= k){
                    return true;
                }
            }
        }
        return false;
    }
}

Better Solution:

//set相当于缓存k+1个不相等的元素,一旦个数超过k+1个,那么每次都会清除掉"队首"元素(set无序,形象化理解是这样,其实是通过nums[i - k + 1]实现的)。因此,如果一个元素加入set,
!set.add()返回true,则说明有两个元素相等且diff<=k;
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                set.remove(nums[i - k - 1]);
            }
            set.add(),如果set包含nums[i],那么返回false,如果不包含,返回true
            if (!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}

Best Solution:

class Solution {
//通过map保存元素下标
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(k > 3000) return false;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && (i - map.get(nums[i]) <= k)) {
                return true;
            } else {
                map.put(nums[i], i);
            }
        }
        return false;
    }
}

leetCode-Contains Duplicate II

标签:包含   color   nta   list   ecs   ica   set   whether   shm   

原文地址:http://www.cnblogs.com/kevincong/p/7900358.html

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