C#解leetcode 219. Contains Duplicate II

该题用到了.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;
    }
}

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

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

 

posted on 2016-03-14 20:13  狂奔的蜗牛163  阅读(348)  评论(0编辑  收藏  举报