Contains Duplicate II

来源:互联网 发布:蜂窝数据漫游是什么 编辑:程序博客网 时间:2024/06/13 13:15

c++

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        if (nums.empty() || nums.size()<=1)            return false;        unordered_set<int> dict;//faster than set<int>        for (size_t i = 0; i < nums.size(); ++i) {            if (dict.find(nums[i]) != dict.end())                return true;            dict.insert(nums[i]);            if (dict.size() > k)                dict.erase(dict.find(nums[i - k]));        }        return false;    }};

python

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        dict = {}        for i in xrange(len(nums)):            if dict.get(nums[i], 'N/A')!='N/A':                return True            dict[nums[i]] = 1;            if len(dict)>k:                dict.pop(nums[i-k])        return False

reference:
https://leetcode.com/discuss/100633/7-lines-cpp-solution-32ms-easy-to-understand

0 0
原创粉丝点击