IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode -- Contains Duplicate II

    csharp25发表于 2017-02-19 22:30:00
    love 0
    题目描述:


    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[i]和nums[j]相等并且i和j的距离小于等于k。


    思路:
    本题考查的还是哈希表的使用,直接用哈希表存每个数字的所有位置。


    实现代码:
    public class Solution {
        public bool ContainsNearbyDuplicate(int[] nums, int k) {
            if(nums == null || nums.Length == 0){
        		return false;
        	}
        	
            var dict = new Dictionary<int ,IList<int>>();
        	for (var i = 0;i < nums.Length; i++){
        		if(!dict.ContainsKey(nums[i])){
        			dict.Add(nums[i], new List<int>(){i});
        		}
        		else{
        			if(dict[nums[i]].Any(x=>(i-x) <= k)){
        				return true;
        			}else{
        				dict[nums[i]].Add(i);
        			}
        		}
        	}        
        	
        	return false;
        }
    }




沪ICP备19023445号-2号
友情链接