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;
}
相关推荐
菜_小_白2 分钟前
codex
linux·vscode·ai
Zhao136824553917 分钟前
国产替代DPE5500百兆以太网控制芯片兼容W5500
嵌入式硬件·物联网
zhangrelay12 分钟前
用ROS2Lyrical实验报告册思路重做蓝桥云课ROS1实验并改进
linux·笔记·学习·ubuntu·机器人
小师兄吃牛肉17 分钟前
C语言篇:内联函数
c语言·开发语言
林兴洋19 分钟前
linux-mtr命令-ping和traceroute的能力合二为一
linux
嘎嘎风19 分钟前
MiniMind 学习笔记之 07 模型怎么学会猜词(旋钮是怎么被拧动的)
算法·源码阅读
OsDepK33 分钟前
OSMDE_v1.9.0已加入FTP与shell功能
linux·运维·服务器
yuehuaxin0138 分钟前
LP20R100FN 同步整流|3C 认证适配器 CCM 工况倒灌、温升超标样机避坑解析
嵌入式硬件·智能家居·适配器模式·智能硬件
和裕1 小时前
定制纸箱刀模费全解析:费用定义与可减免合作场景
大数据·运维·网络·人工智能·算法
白山编程大哥1 小时前
C语言篇:语法进阶
c语言·数据结构·算法