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;
}
相关推荐
麟城Lincoln7 分钟前
【Linux笔记】nfs网络文件系统与autofs(nfsdata、autofs、autofs.conf、auto.master)
linux·网络·笔记·nfs·autofs
Funny-Boy13 分钟前
Reactor (epoll实现基础)
服务器·网络·c++
***似水流年***24 分钟前
Linux任务管理与守护进程
linux·运维·服务器
I AM_SUN27 分钟前
98. 验证二叉搜索树
数据结构·c++·算法·leetcode
O。o.尊都假都31 分钟前
STM32就业前景和下载KEIL软件(保姆级)
stm32·单片机·嵌入式硬件
python算法(魔法师版)37 分钟前
.NET NativeAOT 指南
java·大数据·linux·jvm·.net
unityのkiven1 小时前
C++中析构函数不设为virtual导致内存泄漏示例
开发语言·c++
学习中的码虫1 小时前
数据结构基础排序算法
数据结构·算法·排序算法
「QT(C++)开发工程师」1 小时前
STM32 | FreeRTOS 消息队列
stm32·单片机·嵌入式硬件
正经教主1 小时前
【基础】Windows开发设置入门4:Windows、Python、Linux和Node.js包管理器的作用和区别(AI整理)
linux·windows·python·包管理器