220. Contains Duplicate III
2016-08-06 23:36
295 查看
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.
题意:
求数组中是否存在两个数其下标差不大于k,数值差不大于t。
思路:
使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和j,刚开始i和j都指向0,然后i开始向右走遍历数组,如果i和j之差大于k,则删除并j加1。这样保证了m中所有的数的下标之差都不大于k,然后用map数据结构的lower_bound()函数来找一个特定位置,就是大于或等于nums[i] - t的地方,所有下标小于这个位置的数和nums[i]的差的绝对值会大于t 。然后检测该位置上的数字,如果差小于等于t,则返回true。最后遍历完整个数组返回false。
题意:
求数组中是否存在两个数其下标差不大于k,数值差不大于t。
思路:
使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和j,刚开始i和j都指向0,然后i开始向右走遍历数组,如果i和j之差大于k,则删除并j加1。这样保证了m中所有的数的下标之差都不大于k,然后用map数据结构的lower_bound()函数来找一个特定位置,就是大于或等于nums[i] - t的地方,所有下标小于这个位置的数和nums[i]的差的绝对值会大于t 。然后检测该位置上的数字,如果差小于等于t,则返回true。最后遍历完整个数组返回false。
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { map<int, int> m; int j = 0; for (int i = 0; i < nums.size(); ++i) { if (i - j > k) m.erase(nums[j++]); auto a = m.lower_bound(nums[i] - t); if (a != m.end() && a->first - nums[i] <= t) return true; m[nums[i]] = i; } return false; } };
相关文章推荐
- Leetcode 220. Contains Duplicate III
- 220. Contains Duplicate III
- [LeetCode] 220. Contains Duplicate III 包含重复元素 III
- Leetcode 220. Contains Duplicate III
- leetcode 220. Contains Duplicate III
- 【C++】leetcode 220. Contains Duplicate III
- LeetCode *** 220. Contains Duplicate III (set::lower_bound)
- 220. Contains Duplicate III
- 220. Contains Duplicate III
- 220. Contains Duplicate III
- [LeetCode]220. Contains Duplicate III
- 220. Contains Duplicate III
- 220. Contains Duplicate III
- 217, 219,220. Contains Duplicate I, II, III
- leetcode 220. Contains Duplicate III
- 220. Contains Duplicate III
- [leetcode]220. Contains Duplicate III
- LeetCode 220. Contains Duplicate III
- 220. Contains Duplicate III
- LeetCode 220. Contains Duplicate III *****理解条件,查找表