LeetCode 30 days challenge: Counting Elements

本文详细解析了一种计数特定元素的算法,该算法通过使用哈希表优化查找过程,将时间复杂度从O(n^2)降低到O(n),并提供了C++实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目名称 Counting Elements

题目描述
Given an integer array arr, count element x such that x + 1 is also in arr.

If there’re duplicates in arr, count them seperately.

例子:

Example 1:

Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.

Example 2:

Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.

Example 3:

Input: arr = [1,3,2,3,5,0]
Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.

Example 4:

Input: arr = [1,1,2,2]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.

Constraints:

1 <= arr.length <= 1000
0 <= arr[i] <= 1000

提示
Hide Hint #1
Use hashset to store all elements.

Hide Hint #2
Loop again to count all valid elements.

我的理解
最初的想法就是两层循环,对每一个元素a,找arr数组中是否存在a+1. 时间复杂度大致为o(n^2)。

后来看到了提示,应该用哈希表来解决这个问题,虽然要遍历两次,但是时间复杂度缩减到o(n)。

第一次循环来建立键值对的关系,键为元素实际值,值为元素对应索引。用map数据结构来存储键值信息,对于相同的键,值存储在vector里面。

第二次循环通过遍历map,来查看对于每一个键元素,是否存在键+1的元素。

C++ solution
class Solution {
public:
    int countElements(vector<int>& arr) {
        
        map<int,vector<int>> dict;
        map<int, vector<int>>::iterator iter;
        int cnt = 0;
        for(int i = 0; i < arr.size(); i++){
            
            iter = dict.find(arr[i]);
            if(iter != dict.end())
                dict[arr[i]].push_back(i);
            else
                dict[arr[i]] = {i};
            
        }
        map<int, vector<int>>::iterator iter1;
        for(iter = dict.begin(); iter != dict.end(); iter++){
          iter1 = dict.find(iter->first + 1);
          if(iter1 != dict.end())
              cnt += dict[iter->first].size();
     }
        return cnt;    
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值