标签:
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