LeetCode-217&219&220.Contains Duplicate

来源:互联网 发布:微信爆粉软件 编辑:程序博客网 时间:2024/05/22 05:10

217 https://leetcode.com/problems/contains-duplicate/

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

public bool ContainsDuplicate(int[] nums)     {        HashSet<int> set = new HashSet<int>();        for (int i = 0; i < nums.Length; i++)        {            if (!set.Add(nums[i]))                return true;        }        return false;    }



219 https://leetcode.com/problems/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 jis at most k.

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


220 https://leetcode.com/problems/contains-duplicate-iii/

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

使用SortedSet和加窗法

SortedSet使用的红黑树实现的

另外,使用long而不是int,防止溢出

public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t)        {            int n = nums.Length;            if (t < 0 || k < 1)                return false;            SortedSet<long> set = new SortedSet<long>();            for (int i = 0; i < n; i++)            {                SortedSet<long> subSet = set.GetViewBetween((long)nums[i] - t, (long)nums[i] + t);                if (subSet.Count != 0)                    return true;                if (i >= k)                    set.Remove((long)nums[i - k]);                set.Add((long)nums[i]);            }            return false;        }



0 0