C语言刷题 LeetCode 30天挑战 (七)哈希计数法

//Counting Elements

//Given an integer array arr ,count element x such that x + 1 is also in arr

//lf there're duplicates in arr , count them seperately.

//Example 1:

//Input: arr =1,2,3

//0utput: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

//0utput: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,8

//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

//0utput:2

//Explanation:Two is are counted cause 2 is in arr.

cpp 复制代码
#include <stdio.h>

int countElements(int *arr, int arrSize) {
    // Boolean array to mark presence of elements in the input array.
    int elementExists[1002] = {0}; // Supports values from 0 to 1000

    // Mark the presence of elements in the array
    for (int i = 0; i < arrSize; ++i) {
        elementExists[arr[i]] = 1;
    }

    int returnNum = 0;
    // Check if `arr[i] + 1` exists in the array
    for (int i = 0; i < arrSize; ++i) {
        if (elementExists[arr[i] + 1]) {
            returnNum++;
        }
    }

    return returnNum;
}

int main()
{
    int arr[] = {1,1,2,2};
    printf("%d",countElements(arr,sizeof(arr)/sizeof(arr[0])));
    return 0;
}
相关推荐
Jared_devin3 分钟前
单头、多头 Self-Attention可视化
人工智能·pytorch·深度学习·算法·机器学习·pycharm
君生我老4 分钟前
Linux动静态库
linux·服务器
Jackson_GJH11 分钟前
C++虚函数、虚继承、虚基类
c++·c++基础
wuyk55514 分钟前
18.Kruskal 算法:用最短的边连成一张网
开发语言·算法·图论
一条破秋裤14 分钟前
24_MPU6050结构参数与寄存器基础
stm32·嵌入式硬件·学习
宵时待雨19 分钟前
linux笔记归纳19:网络层协议IP
linux·网络·笔记·网络协议·tcp/ip
码匠许师傅27 分钟前
【C++三方组件】开篇总论:为什么需要以及如何选型?
开发语言·c++
h_a_o777oah33 分钟前
【Games101】C++ 软光追:光线追踪的求交逻辑和 BVH 提效实现及代码实现细节
c++·计算机图形学·光线追踪·games101·bvh·求交算法·软件渲染
cvby42 分钟前
C++11--右值引用和移动语义
开发语言·c++
ZLG_zhiyuan1 小时前
低空测试“升维”:ZUS系列示波器如何破解复杂信号的“测与析”难点?
单片机·嵌入式硬件