首页 > 其他 > 详细

Contains Duplicate II ——LeetCode

时间:2015-06-08 01:00:18      阅读:175      评论:0      收藏:0      [点我收藏+]

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

题目大意:给定一个数组,和一个整数k,找出是否有两个不同的下标使得nums[i] = nums[j] ,并且i和j相距不超过k。

解题思路:使用两个map,保存一个数的两个下标,一大一小,并在遍历数组时更新它。

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums==null||nums.length==0){
            return false;
        }
        Map<Integer,Integer> minMap = new HashMap<>();
        Map<Integer,Integer> maxMap = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(minMap.get(nums[i])!=null){
                int min=minMap.get(nums[i]);
                if(maxMap.get(nums[i])!=null){
                    int max=maxMap.get(nums[i]);
                    if((min!=max&&max-min<=k)||i-max<=k){
                        return true;
                    }
                    minMap.put(nums[i],max);
                    maxMap.put(nums[i],i);
                    continue;
                }
            }
            minMap.put(nums[i],i);
            maxMap.put(nums[i],i);
        }
        return false;
    }

 

Contains Duplicate II ——LeetCode

原文:http://www.cnblogs.com/aboutblank/p/4559988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!