您的位置:首页 > 大数据 > 人工智能

LeetCode - 217/219/220 - Contains Duplicate

2017-07-31 20:08 204 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: