LeetCode
来源:互联网 发布:花刺代理软件 编辑:程序博客网 时间:2024/06/10 05:20
217. 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.
问数组中是否存在重复的数。
用map存一下,若是发现存在,便返回true。时间复杂度O(n),空间复杂度O(n)
class Solution {public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, bool> vis; for (auto x: nums) { if (vis.find(x) != vis.end()) return true; vis[x] = true; } return false; }};
219. 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 absolute difference between i and j is at most k.
在上一题的基础上,添加了相同的数i,j距离不大于k的条件。
还是用map存一下做判断。时间复杂度O(n),空间复杂度O(n)
class Solution {public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> vis; for (int i = 0; i < nums.size(); ++i) { if (vis.find(nums[i]) != vis.end() && i - vis[nums[i]] <= k) return true; vis[nums[i]] = i; } return false; }};
220. 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 absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
给定一个整数数组nums[],查找是否存在两个下标i和j,| nums[i] - nums[j] | <= t && i - j <= k
建立一个set,将所有下标满足条件的数都存放进去。假设当前遍历到nums[i],我们要在set中找到是否有满足: nums[i] - t <= x <= nums[i] + t 的位置。用lower_bound二分查询set返回下标,然后再判断其值是否满足条件即可。时间复杂度O(nlogn(k)),空间复杂度O(k)
用long long是因为,有INT_MIN值的出现,-t 后会爆int
class Solution {public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (k <= 0 || t < 0) return false; set<long long> vis; for (int i = 0; i < nums.size(); ++i) { if (i > k) vis.erase(nums[i-k-1]); auto pos = vis.lower_bound((long long)nums[i] - t); if (pos != vis.end() && abs(*pos - nums[i]) <= t) return true; vis.insert((long long)nums[i]); } return false; }};
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Tempter of the Bone
- 红与黑(dfs水题)
- jQuery对复选框(checkbox)的全选,全不选,反选等的操作
- 如何寻找数组中的最大值和最小值
- 如何将 iOS 项目的编译速度提高5倍
- LeetCode
- 封装,继承,多态
- UITextView实时跟踪输入文字的个数,超过禁止输入并阶段
- linux内存管理slab算法之slab初始化
- 杭电ACM题目分类大全
- 功能展示——ExpandableListView中嵌套GridView
- 递归删除文件夹
- 浅析《新一代人工智能发展规划》【智库2861】
- iOS音频播放 (八):NowPlayingCenter和RemoteControl