219. Contains Duplicate II

219. Contains Duplicate II                   

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

问题描述:给定一个整数数组和整数k,找出该数组中是否存在两个不同的下标和j(i!=j),是的nums[i]=nums[j],且|i-j|<=k。

分析:最简单的思路是:循环遍历数组,对下标为i的元素,查找该元素的k个元素中是否有与nums[i]相等的元素,若有相等的则返回true;若不相等则继续循环,直至结束。使用两层循环:外层循环的结束条件是i<nums.length,内层循环的结束条件:当 m = (i+k < nums.length - 1) ? (i+k) (nums.length-1)。

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums.length < 2)
            return false;
        int m;
        for(int i = 0;i < nums.length;i++){
            if(i+k < nums.length - 1)
                m = i + k;
            else
                m = nums.length-1;
            // m = (i+k <= nums.length - 1) ? (i+k) : (nums.length-1);
            for(int j = i+1;j <= m;j++){
                if(nums[i] == nums[j])
                    return true;
            }          
        }
        return false;
    }
}


这是最开始自己的代码,但是提交代码时出现了如下问题:

最后AC的代码:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
         if(nums.length < 2)
	            return false;
        if(k > 3000)
            return false;
        for(int i = 0;i < nums.length;i++){
            int m = (i+k < nums.length - 1) ? (i+k) : (nums.length-1);
            for(int j = i+1; j <= m;j++){
                if(nums[i] == nums[j])
                    return true;
            }           
        }
        return false;
    }
}

后来参考了另一种方法:将数组存入HashMap中,<K,V>分别对应<nums[i],i>,即nums[i]是唯一的。循环遍历数组,若nums[i]已存在hashMap中,则判断当前下标i与nums[i]在hashMap中对应的下标之差是否小于等于k,若满足则返回true;否则继续循环,直至循环结束。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值