• 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;
        }
    }

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

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

  • 相关阅读:
    遥远的国度(D12 树链剖分)
    Codechef DGCD Dynamic GCD(D12 树上GCD)
    html总结
    数据库大总结
    html笔记
    Linux常用快捷键
    进程
    多进程
    进程介绍
    网络并发
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/5276970.html
Copyright © 2020-2023  润新知