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; }
- LeetCode-217&219&220.Contains Duplicate
- Contains Duplicate - LeetCode 217
- LeetCode 217:Contains Duplicate
- leetcode 217: Contains Duplicate
- Leetcode[217]-Contains Duplicate
- 【leetcode】【217】Contains Duplicate
- LeetCode 217 Contains Duplicate
- leetcode-217-Contains Duplicate
- Leetcode 217 Contains Duplicate
- Leetcode 217 Contains Duplicate
- leetcode 217:Contains Duplicate
- LeetCode 217: Contains Duplicate
- LeetCode #217 Contains Duplicate
- leetCode #217 Contains Duplicate
- leetcode 217: Contains Duplicate
- Leetcode #217 Contains Duplicate
- [Leetcode]#217 Contains Duplicate
- [LeetCode 217] Contains Duplicate
- BZOJ2815: [ZJOI2012]灾难
- linux socket 网络进程间通信 (光谷王凯的博客)
- Android SlidingMenu Demo
- Spring自动装配Bean属性的四种方式
- java二分搜索算法
- LeetCode-217&219&220.Contains Duplicate
- 数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
- 图像分析:二值图像连通域标记-基于行程的标记方法
- 2014 奇怪的分式
- 【poj 1182】 食物链 题解&代码(C++)
- CSU1093: Caps Lock
- Android动态加载—Res文件
- util小类集合
- UE编辑语法高亮显示及大括号自动对齐设置