Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 219. Contains Duplicate II #219

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 219. Contains Duplicate II #219

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

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.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

 

这道题是之前那道 Contains Duplicate 的延伸,不同之处在于那道题只要判断下数组中是否有重复值,而这道题限制了数组中只许有一组重复的数字,而且其坐标差不能超过k。首先需要一个 HashMap,来记录每个数字和其坐标的映射,然后需要一个变量d来记录第一次出现重复数字的坐标差。由于题目要求只能有一组重复的数字,所以在遇到重复数字时,首先判断d是否已经存了值,如果d已经有值了,说明之前有过了重复数字,则直接返回 false 即可。如果没有,则此时给d附上值。在网上看到有些解法在这里就直接判断d和k的关系然后返回结果了,其实这样是不对的。因为题目要求只能有一组重复数,就是说如果后面又出现了重复数,就没法继续判断了。所以正确的做法应该是扫描完整个数组后在判断,先看d有没有存入结果,如果没有,则说明没出现过重复数, 返回 false 即可。如果d有值,再跟k比较,返回对应的结果。OJ 的 test case 没有包含所有的情况,比如当 nums = [1, 2, 3, 1, 3], k = 3 时,实际上应该返回 false,但是有些返回 true 的算法也能通过 OJ,个人认为正确的解法应该如 评论区十二楼 所示,但是由于后来题目要求变了,那么就没啥歧义了,正确解法如下:

 

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) {
            if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;
            else m[nums[i]] = i;
        }
        return false;
    }
};

 

Github 同步地址:

#219

 

类似题目:

Contains Duplicate

Contains Duplicate III

 

参考资料:

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

https://leetcode.com/problems/contains-duplicate-ii/discuss/61372/Simple-Java-solution

https://leetcode.com/problems/contains-duplicate-ii/discuss/61390/C%2B%2B-solution-with-unordered_set

 

LeetCode All in One 题目讲解汇总(持续更新中...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant