首页 > Windows开发 > 详细

C#解leetcode 219. Contains Duplicate II

时间:2016-03-14 21:41:04      阅读:271      评论:0      收藏:0      [点我收藏+]

该题用到了.NET 3.5在System.Collections.Generic命名空间中包含一个新的集合类:HashSet<T>的Add()方法,详细信息请看转载:C# HashSet 用法

 

题目:

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 jis at most k.

解答:

public class Solution {
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
      HashSet<int> hashSet = new HashSet<int>();
      for (int i = 0; i < nums.Length; i++) {
            if (i > k) {
                hashSet.Remove(nums[i - k - 1]);
            }
            if (!hashSet.Add(nums[i])) {
                return true;
            }
        }
 
       return false;
    }
}

之所以可以用这个答案,主要是因为集合的一个特性:

在集合中所有的元素都只能存在一次,如果向集合中添加已经存在的元素会失败

 

C#解leetcode 219. Contains Duplicate II

原文:http://www.cnblogs.com/xiaohua92/p/5276970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!