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;
}
相关推荐
爪哇学长几秒前
双指针算法详解:原理、应用场景及代码示例
java·数据结构·算法
爱摸鱼的孔乙己3 分钟前
【数据结构】链表(leetcode)
c语言·数据结构·c++·链表·csdn
Dola_Pan4 分钟前
C语言:数组转换指针的时机
c语言·开发语言·算法
繁依Fanyi17 分钟前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse
C-cat.17 分钟前
Linux|环境变量
linux·运维·服务器
yunfanleo32 分钟前
docker run m3e 配置网络,自动重启,GPU等 配置渠道要点
linux·运维·docker
烦躁的大鼻嘎33 分钟前
模拟算法实例讲解:从理论到实践的编程之旅
数据结构·c++·算法·leetcode
嵌入式大圣36 分钟前
单片机结合OpenCV
单片机·嵌入式硬件·opencv
IU宝37 分钟前
C/C++内存管理
java·c语言·c++
fhvyxyci38 分钟前
【C++之STL】摸清 string 的模拟实现(下)
开发语言·c++·string