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;
}
相关推荐
战血石LoveYY18 分钟前
Integer类型超限,导致数据异常
java·算法
李永奉18 分钟前
杰理可视化SDK开发-【BUG】配置“TWS两边同时按消息使能”功能后,按键单击功能无效失灵
开发语言·单片机·嵌入式硬件·物联网·bug
会周易的程序员19 分钟前
从零构建多核CPU负载自适应控制系统
linux·c++·笔记·物联网·测试工具
紫金修道27 分钟前
PnP算法介绍(Perspective-n-Point)
算法
ZXXstarstar32 分钟前
2026年电池安全使用年限的量化决策:什么时间到期最需要替换?
linux·运维·服务器·电池
程序猿编码44 分钟前
用C++从零开始造一个微型GPT,不借助任何第三方库
开发语言·c++·gpt·模型推理
执迷不悟8231 小时前
51单片机--中断/定时/PWM
单片机·嵌入式硬件·51单片机
网络小白不怕黑1 小时前
httpd监控
linux·运维·服务器
qz5zwangzihan11 小时前
题解:Atcoder Beginner Contest abc466 F - Many Mod Calculation
c++·题解·优先队列·atcoder·大根堆·abc466·abc466f
froyoisle2 小时前
CSP 真题解析:[CSP-J 2019-T4] 加工零件
c++·算法·bfs·csp-j·算法竞赛·信息学·信奥赛