219 Contains Duplicate II

原创 2018年04月12日 12:39:00

Contains Duplicate II
判断数组中是否存在距离小于k的两个相同元素

讨论区中一个c++答案:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k)
    {
       unordered_set<int> s;

       if (k <= 0) return false;
       if (k >= nums.size()) k = nums.size() - 1;

       for (int i = 0; i < nums.size(); i++)
       {
           if (i > k) s.erase(nums[i - k - 1]);//保持set中仅有k个元素
           if (s.find(nums[i]) != s.end()) return true;
           s.insert(nums[i]);
       }

       return false;
    }
};

使用map:

bool containsNearbyDuplicate(vector<int>& nums, int k) {

    unordered_map<int,int> nmap;
    for (int i = 0; i <nums.size();i++)
    {
        if (nmap.count(nums[i]) == 0)
            nmap[nums[i]] = i;
        else if (i - nmap[nums[i]] <=k)
            return true;
        else
            nmap[nums[i]] = i;//重复元素距离大于k时更新该元素为后者
    }

    return false;

各种异常问题解决

实际异常一: libcpmtd.lib(xmbtowc.obj) : error LNK2001: unresolved external symbol __CrtDbgReport Debug/...
  • danelumax2
  • danelumax2
  • 2013-11-01 21:32:42
  • 2742

iOS开发常见错误代码对照表---真机调试常见错误及解决方案

iOS真机调试常见错误及解决方案 地址https://developer.apple.com/library/ios/#technotes/tn2250/_index.html#//apple_r...
  • wangeclipse
  • wangeclipse
  • 2013-11-30 17:03:45
  • 4361

leetcode 219: Contains Duplicate II

leetcode 219: Contains Duplicate II java c++ python
  • xudli
  • xudli
  • 2015-05-29 15:02:09
  • 8591

【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】

【219-Contains Duplicate II(包含重复元素II)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-...
  • DERRANTCM
  • DERRANTCM
  • 2015-08-29 06:36:21
  • 3614

219. Contains Duplicate II [easy] (Python)

题目链接https://leetcode.com/problems/contains-duplicate-ii/题目原文 Given an array of integers and an int...
  • coder_orz
  • coder_orz
  • 2016-06-14 19:59:14
  • 1953

LeetCode 219:Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices i...
  • sunao2002002
  • sunao2002002
  • 2015-05-31 18:41:22
  • 3821

leetcode_c++:Contains Duplicate II(219)

题目Given an array of integers and an integer k, find out whether there are two distinct indices i and...
  • mijian1207mijian
  • mijian1207mijian
  • 2016-06-18 13:33:40
  • 310

219 Contains Duplicate II

class Solution {     public boolean containsNearbyDuplicate(int[] nums, int k) {     Map map = new...
  • gyn18744026959
  • gyn18744026959
  • 2015-07-22 21:22:32
  • 168

[219] Contains Duplicate II

给定一个数组和一个整型k,判断数组中是否有两个相等的值的距离小于k。
  • camlot_
  • camlot_
  • 2016-07-26 11:17:43
  • 90

#219 Contains Duplicate II

题目: Given an array of integers and an integer k, find out whether there there are two distinct in...
  • private_void
  • private_void
  • 2015-06-02 21:23:43
  • 269
收藏助手
不良信息举报
您举报文章:219 Contains Duplicate II
举报原因:
原因补充:

(最多只允许输入30个字)