Skip to content

Latest commit

 

History

History

1426.Counting Elements

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

给你一个整数数组 arr, 对于元素 x ,只有当 x + 1 也在数组 arr 里时,才能记为 1 个数。

如果数组 arr 里有重复的数,每个重复的数单独计算。

 

示例 1:

输入:arr = [1,2,3]
输出:2
解释:1 和 2 被计算次数因为 2 和 3 在数组 arr 里。

示例 2:

输入:arr = [1,1,3,3,5,5,7,7]
输出:0
解释:所有的数都不算, 因为数组里没有 2、4、6、8。

 

提示:

  • 1 <= arr.length <= 1000
  • 0 <= arr[i] <= 1000

解法

Python3

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

Java

class Solution {
    public int countElements(int[] arr) {
        Set<Integer> s = new HashSet<>();
        for (int num : arr) {
            s.add(num);
        }
        int res = 0;
        for (int num : arr) {
            if (s.contains(num + 1)) {
                ++res;
            }
        }
        return res;
    }
}

C++

class Solution {
public:
    int countElements(vector<int>& arr) {
        unordered_set<int> s;
        for (int num : arr) s.insert(num);
        int res = 0;
        for (int num : arr)
            if (s.count(num + 1)) ++res;
        return res;
    }
};

Go

func countElements(arr []int) int {
	s := make(map[int]bool)
	for _, num := range arr {
		s[num] = true
	}
	res := 0
	for _, num := range arr {
		if s[num+1] {
			res++
		}
	}
	return res
}

...