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;
}
相关推荐
夜思红尘24 分钟前
算法--双指针
python·算法·剪枝
人工智能训练26 分钟前
OpenEnler等Linux系统中安装git工具的方法
linux·运维·服务器·git·vscode·python·ubuntu
散峰而望42 分钟前
【算法竞赛】C++函数详解:从定义、调用到高级用法
c语言·开发语言·数据结构·c++·算法·github
冷凝雨1 小时前
复数乘法(C & Simulink)
c语言·开发语言·信号处理·simulink·dsp
IT阳晨。1 小时前
【STM32】天气预报项目
stm32·单片机·嵌入式硬件
CoderCodingNo1 小时前
【GESP】C++五级真题(贪心思想考点) luogu-B4071 [GESP202412 五级] 武器强化
开发语言·c++·算法
我有一些感想……1 小时前
An abstract way to solve Luogu P1001
c++·算法·ai·洛谷·mlp
前端小L1 小时前
双指针专题(三):去重的艺术——「三数之和」
javascript·算法·双指针与滑动窗口
在风中的意志1 小时前
[数据库SQL] [leetcode] 2388. 将表中的空值更改为前一个值
数据库·sql·leetcode
QT 小鲜肉1 小时前
【Linux命令大全】001.文件管理之which命令(实操篇)
linux·运维·服务器·前端·chrome·笔记