LeetCode C++ 1426. Counting Elements【Array/Hash Table】简单
发布日期:2021-07-01 02:58:20
浏览次数:3
分类:技术文章
本文共 1190 字,大约阅读时间需要 3 分钟。
Given an integer array arr
, count how many elements x
there are, 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: 2Explanation: 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: 0Explanation: 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: 3Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
Example 4:
Input: arr = [1,1,2,2]Output: 2Explanation: Two 1s are counted cause 2 is in arr.
Example 5:
Input: arr = [1,1,2]Output: 2Explanation: Both 1s are counted because 2 is in the array.
Constraints:
1 <= arr.length <= 1000
0 <= arr[i] <= 1000
题意:给出一个整数数组 arr
, 对于元素 x
,只有当 x + 1
也在数组 arr
里时,才能记为 1
个数。如果数组 arr
里有重复的数,每个重复的数单独计算。
解法 哈希表
class Solution { public: int countElements(vector & arr) { int cnt[1010] = { 0}, ans = 0; for (const int &v : arr) ++cnt[v]; for (int i = 0; i <= 1000; ++i) if (cnt[i] && cnt[i + 1]) ans += cnt[i]; return ans; }};
运行效率如下:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:7.6 MB, 在所有 C++ 提交中击败了48.15% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/111403068 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年05月06日 18时55分13秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
[转帖]Robots.txt指南
2019-05-01
正则表达式简介(微软)--6.优先权顺序
2019-05-01
多用户与多租户的区别
2019-05-01
Python自动化运维 - day14 - JavaScript基础
2019-05-02
oracle保存小数点前为"0"的问题
2019-05-02
linux sar 命令详解
2019-05-02
ipvsadm 安装配置
2019-05-02
Linux shell脚本的字符串截取
2019-05-02
数据库复习(4)
2019-05-02
1小时点击量破千万!阿里巴巴首发:MySQL高级调优笔记!全是技术重点
2019-05-02
这个GItHub上的Java项目开源了 2021最全的Java架构面试复习指南
2019-05-02
Proftpd MySQL [Step by Step]
2019-05-02
EFI Shell 命令参考
2019-05-02
HP-UX oracle RAC 双机实践
2019-05-02
解决SHELL脚本中的export无法生效的问题【转】
2019-05-02
linux中的sh脚本语法【转】
2019-05-02
区别数据结构中的堆栈与内存中的堆栈的个人总结【转】
2019-05-02
c++中冒号(:)和双冒号(::)的用法【转】
2019-05-02