Skip to content

Latest commit

 

History

History
199 lines (169 loc) · 3.46 KB

File metadata and controls

199 lines (169 loc) · 3.46 KB

中文文档

Description

Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately.

 

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 is no 2, 4, 6, or 8 in arr.

 

Constraints:

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

Solutions

Python3

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

Java

class Solution {
    public int countElements(int[] arr) {
        int ans = 0;
        for (int x : arr) {
            for (int v : arr) {
                if (x + 1 == v) {
                    ++ans;
                    break;
                }
            }
        }
        return ans;
    }
}
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) {
        int ans = 0;
        for (int x : arr) {
            for (int v : arr) {
                if (x + 1 == v) {
                    ++ans;
                    break;
                }
            }
        }
        return ans;
    }
};
class Solution {
public:
    int countElements(vector<int>& arr) {
        unordered_set<int> s(arr.begin(), arr.end());
        int ans = 0;
        for (int x : arr) {
            ans += s.count(x + 1);
        }
        return ans;
    }
};

Go

func countElements(arr []int) int {
	ans := 0
	for _, x := range arr {
		for _, v := range arr {
			if x+1 == v {
				ans++
				break
			}
		}
	}
	return ans
}
func countElements(arr []int) int {
	s := map[int]bool{}
	for _, x := range arr {
		s[x] = true
	}
	ans := 0
	for _, x := range arr {
		if s[x+1] {
			ans++
		}
	}
	return ans
}

JavaScript

/**
 * @param {number[]} arr
 * @return {number}
 */
var countElements = function (arr) {
    let ans = 0;
    for (const x of arr) {
        ans += arr.includes(x + 1);
    }
    return ans;
};
/**
 * @param {number[]} arr
 * @return {number}
 */
var countElements = function (arr) {
    const s = new Set();
    for (const x of arr) {
        s.add(x);
    }
    let ans = 0;
    for (const x of arr) {
        if (s.has(x + 1)) {
            ++ans;
        }
    }
    return ans;
};

...