leetcode题目.22——Countiing Elements

题目:
Given an integer array arr。count element x such that x+1 is also in arr.
if there’re duplicates in arr,count them seperately
给定一个整数的阵列,有多少个数字元素x当其x+1之后依然存在于arr数组内。
在这里插入图片描述
Constraints:
· 1 <= arr.length <= 1000
· 0 <= arr[i] <= 1000

int countElements(int* arr, int arrSize){
    //input:
    //arr: [1,3,2,3,5,0], arrSize:6
    //plus  1,4,3,4,6,1
    //found 1,0,1,0,0,1
    //相加  1+0+1+0+0+1=3
    
    int arrPlus1[arrSize];
    for (int i = 0; i < arrSize; i++){
        plus1[i] = arr[i] + 1;
    }
    int found[arrSize]:
    for(int i = 0; i < arrSize; i++){
        //检查plus1[i]有没有在arr里出现
        int count = 0;
        for (int j = 0; j < arrSize; j++){
            if(arr[j] == plus1[i]){
                count++;
            }
        }
        if(count >= 1){
            found[i] = 1;
        else
            found[i] = 0;
        }
    }
    int count = 0;
    for(int i = 0; i <= arrSize; I++){
        count+ =found[i];
    }
   return count;
}

上述方法产生了额外的阵列来储存plus1和found,简化后有以下形式:

int coountElement(int* arr, int arrSize){
    int count = 0;
    for (int i = 0; i < arrSize; i++){
        int x = arr[i];
        int xPlus1 = x + 1;

        bool isFound = false;
        for (in j = 0; j < arrSize; j++){
            if (arr[j] == xPlus[i]){
                isFound = true;
            }
            if (isFound){
                count ++;
            }
        }
        return count;
    }
}

int coountElement(int* arr, int arrSize){
    //因为数字是0~1000之间,所以会加到1001
    //一开始全部都当作没找到
    bool isFound[1002] = {false};//isFound[0]~isFound[1001]

    for (i = 0; i < arrSize; i++){
        isFound[arr[i]] = true;
    }

    int count = 0;
    for (int i = 0; i < arrSize; i++){
        int x = arr[i];
        int xPlus1 = x + 1;
        if (isFound[xPlus1]){
            count++;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值