Leetcode-存在重复元素 IIC++实现

        给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

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

思路:从左到右遍历数组,如果当前元素哈希表里没有||有该元素但不符合abs(i-j)<=k的条件的时候,更新哈希表中num值的下标,若存在该元素且满足下标条件则返回true

 unordered_map::count()是C++中的内置方法,用于通过给定 key 对unordered_map中存在的元素数量进行计数。

        注意:由于unordered_map不允许存储具有重复键的元素,因此count()函数本质上检查unordered_map中是否存在具有给定键的元素。

用法

size_type count(Key);

参数:此函数接受单个参数 key ,需要在给定的unordered_map容器中进行检查。

返回值:如果Map中存在具有给定键的值,则此函数返回1,否则返回0。

以下示例程序旨在说明unordered_map::count()函数:

// C++ program to illustrate the  
// unordered_map::count() function 
  
#include<iostream> 
#include<unordered_map> 
  
using namespace std; 
  
int main() 
{ 
    // unordered map 
    unordered_map<int , string> umap; 
      
    // Inserting elements into the map 
    umap.insert(make_pair(1,"Welcome")); 
    umap.insert(make_pair(2,"to")); 
    umap.insert(make_pair(3,"GeeksforGeeks")); 
      
    // Check if element with key 1 is present using  
    // count() function 
    if(umap.count(1)) 
    { 
        cout<<"Element Found"<<endl; 
    } 
    else
    { 
        cout<<"Element Not Found"<<endl;     
    } 
      
    return 0; 
}

输出:

Element Found

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值