LeetCode Counting Elements (Python)

Posted by 小明MaxMing on April 26, 2020

题目

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.

解题思路

将数组转换成set,遍历set中的每个元素x,检查x+1是否出现在set中

代码

class Solution:
    def countElements(self, arr: List[int]) -> int:
        return len([0 for x in arr if (x + 1) in set(arr)])

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅