1426. Counting Elements
選択した UI 言語に合わせて問題文をロシア語から翻訳します。コードは変更しません。
Дан 整数 配列 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 表示.
有効な求人はまだありません。