leetcode--Contains Duplicate II

来源:互联网 发布:淘宝联盟权益推广 编辑:程序博客网 时间:2024/06/06 18:38

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


题意:给定一个数组和整数k,在数组中查找是否存在两个序号i和j,使nums[i]=nums[j],并且i和j的差最多是k

分类:数组,Hash


解法1:如果两层遍历。时间复杂度是O(n^2),会超时。

和Contains Duplicate类似,我们只遍历一次数组,使用hashMap来记录遍历过的整数,key为这个整数,value为整数所在的序号

如果在遍历过程中发现了重复,比较当前序号和hashmap中的序号,判断差是否小于k,如果是,则返回真,否则继续遍历

[java] view plain copy
  1. public class Solution {  
  2.     public boolean containsNearbyDuplicate(int[] nums, int k) {  
  3.         HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();         
  4.         for(int i = 0;i<nums.length;i++){  
  5.             if(map.containsKey(nums[i])){  
  6.                 if(i-map.get(nums[i])<=k){  
  7.                     return true;  
  8.                 }else{  
  9.                     map.put(nums[i], i);  
  10.                 }  
  11.             }else{  
  12.                 map.put(nums[i], i);  
  13.             }  
  14.         }  
  15.         return false;  
  16.     }  
  17. }  

原文链接

原创粉丝点击