1426. Counting Elements
题目文本会按所选界面语言从俄语翻译;代码保持不变。
Дан 整数 数组 arr, посчитайте, сколько elementов x в нем есть таких, что x + 1 также находится в arr. Если в arr есть дубликаты, считайте их отдельно.
示例:
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
C# 解法
匹配/原始public class Solution {
public int CountElements(int[] arr) {
int count = 0;
foreach (int x in arr) {
if (IntegerInArray(arr, x + 1)) {
count++;
}
}
return count;
}
public bool IntegerInArray(int[] arr, int target) {
foreach (int x in arr) {
if (x == target) {
return true;
}
}
return false;
}
}
C++ 解法
自动草稿,提交前请检查#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int CountElements(vector<int>& arr) {
int count = 0;
foreach (int x in arr) {
if (IntegerInArray(arr, x + 1)) {
count++;
}
}
return count;
}
public bool IntegerInArray(vector<int>& arr, int target) {
foreach (int x in arr) {
if (x == target) {
return true;
}
}
return false;
}
}
Java 解法
匹配/原始class Solution {
public int countElements(int[] arr) {
int count = 0;
for (int x : arr) {
if (integerInArray(arr, x + 1)) {
count++;
}
}
return count;
}
public boolean integerInArray(int[] arr, int target) {
for (int x : arr) {
if (x == target) {
return true;
}
}
return false;
}
}
JavaScript 解法
匹配/原始class Solution {
countElements(arr) {
let count = 0;
for (let x of arr) {
if (this.integerInArray(arr, x + 1)) {
count++;
}
}
return count;
}
integerInArray(arr, target) {
for (let x of arr) {
if (x === target) {
return true;
}
}
return false;
}
}
Python 解法
匹配/原始class Solution:
def countElements(self, arr: List[int]) -> int:
def integerInArray(arr, target):
for x in arr:
if x == target:
return True
return False
count = 0
for x in arr:
if integerInArray(arr, x + 1):
count += 1
return count
Go 解法
匹配/原始package main
func countElements(arr []int) int {
count := 0
for _, x := range arr {
if integerInArray(arr, x+1) {
count++
}
}
return count
}
func integerInArray(arr []int, target int) bool {
for _, x := range arr {
if x == target {
return true
}
}
return false
}
Algorithm
Создайте вспомогательную функцию для проверки, содержится ли element в 数组е.
Итерируйте по каждому elementу 数组а и используйте вспомогательную функцию для проверки, содержится ли element x + 1 в 数组е.
Увеличьте счетчик, если x + 1 найден, и return значение счетчика.
😎
Vacancies for this task
活跃职位 with overlapping task tags are 已显示.
目前还没有活跃职位。