4月30天leetcode训练-Day7

本文详细解析了一种计数元素的算法,该算法用于统计数组中满足特定条件(即元素加1仍在数组中)的元素数量。通过示例展示了算法的具体实现过程,包括输入输出示例、解题思路及代码实现,特别关注了重复元素的处理。

Day27-Counting 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.

给一个数组,问数组中有多少个元素其加1所得的数还在数组中。

Example

Example 1:

Input: arr = [1,2,3]
Output: 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]
Output: 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,0]
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]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.

解法一:

这道题应该还算比较简单吧(因为我自己想出来了。。。)首先想到的就是先把数组排序,然后遍历数组,看当前元素加1与后一个元素是否相等就行了,当然这有个小难点就是数组中有重复的数字也要算上,这里我们可以设置一个变量count表示每个元素的重复数字有多少个,初始值设为1,然后遇到不是重复数字的检测其是否符合标准,如果符合要求,我们的结果值就加上count,因为当前元素符合标准说明总共有count个重复元素也符合标准。如果不符合要求就继续向后遍历,并且把count更新为1.

class Solution:
    def countElements(self, arr: List[int]) -> int:
        result = 0
        arr.sort()
        i = 0
        while i < len(arr) - 1:
            count = 1
            print(i)
            while i < len(arr) - 1 and arr[i] == arr[i + 1]:
                i += 1
                count += 1
            print(i)
            if i >= len(arr) - 1:
                break
            else:
                if arr[i] + 1 == arr[i + 1]:
                    result += count
            i += 1
        return result

这道题的空间复杂度为O(1),没有用到额外的空间,但是时间复杂度似乎也不是O(N),因为用了python的sort函数,这个函数的时间复杂度值得考虑。。。

python 的sort()时间复杂度最坏O(nlogn),空间复杂度为O(n).其内部机制为Timesort

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值