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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 1469. Find All The Lonely Nodes【Tree/DFS/BFS】简单
下一篇:LeetCode C++ 剑指 Offer 64. 求1+2+…+n【Bit Manipulation】中等

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年05月02日 08时09分38秒