LeetCode C++ 1426. Counting Elements【Array/Hash Table】简单
发布日期:2021-07-01 02:58:20
浏览次数:2
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2024年05月02日 08时09分38秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
架构师进阶必看!架构师的工作都干些什么?
2019-05-02
详解RDMA架构和技术原理
2019-05-02
Virtio技术架构简明分析
2019-05-02
浅谈数据库高可用性(HA)技术
2019-05-02
许式伟的架构课
2019-05-02
Linux调试工具
2019-05-02
用Eclipse和GDB构建ARM交叉编译和在线调试环境
2019-05-02
cfs 完全公平调度
2019-05-02
如何判断自己是否具有成为一名优秀程序员的潜质
2019-05-02
创业公司和求职者都应看的九个面试题
2019-05-02
内核的链接脚本文件vmlinux.lds.S
2019-05-02
Ubuntu下 rsync同步文件实例
2019-05-02
安装Samba时遇到错误
2019-05-02
Linux Shell编程入门
2019-05-02
EMACS利用etags查阅大型工程代码
2019-05-02
C++名稱空間(Namespace)的介绍
2019-05-02
通过源码查看Android 版本
2019-05-02
getopts命令详解
2019-05-02
Java接口详解
2019-05-02