你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / C专栏
LeetCode -- Contains Duplicate II
 
题目描述:
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 difference between i and j is at most k.


在一个数组nums中试着找到两个数nums[i]和nums[j],其中,i与j的距离要小于等于k。如果找到,返回true,否则返回false。


思路:


一次遍历num[i...n),哈希存每个数的位置,如果nums[i]已经出现,就判断上次出现的位置与当前位置的距离是否小于等于k。如果是,返回true;否则,更新Hash[nums[i]]的位置=i。






实现代码:



public class Solution {
    public bool ContainsNearbyDuplicate(int[] nums, int k) 
    {
        var hash = new Dictionary();
    	for(var i = 0;i < nums.Length; i++){
    		if(!hash.ContainsKey(nums[i])){
    			hash.Add(nums[i],i);
    		}
    		else{
    			if(Math.Abs(hash[nums[i]] - i) <= k){
    				return true;
    			}
    			else{
    				hash[nums[i]] = i;
    			}
    		}
    	}
    	
    	return false;
    }
}

  推荐精品文章

·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 
·2023年7月目录
·2023年6月目录 
·2023年5月目录
·2023年4月目录 
·2023年3月目录 
·2023年2月目录 
·2023年1月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089