План курса / Все задачи / Алгоритмы и структуры данных
Наличие повторений
легко
# решено
Дан массив целых чисел nums, верни true, если любое значение встречается хотя бы два раза, и верни false, если все элементы уникальны.
Пример 1:
Ввод: nums = [1,4,3,1]
Вывод: true
Объяснение: элемент со значением 1 встречается два раза в 0 и 3 индексе.
Пример 2:
Ввод: nums = [1,2,3,4]
Вывод: false
Объяснение: все элементы уникальны.
Ограничения:
len(nums) >= 1
public class Solution
{
public static bool ContainsDuplicate(List<int> nums)
{
var seen = new HashSet<int>();
foreach (var x in nums)
{
if (seen.Contains(x))
{
return true;
}
seen.Add(x);
}
return false;
}
}
#include <vector>
#include <unordered_set>
using namespace std;
bool containsDuplicate(const vector<int>& nums) {
unordered_set<int> seen;
for (int x : nums) {
if (seen.count(x)) {
return true;
}
seen.insert(x);
}
return false;
}
package main
func containsDuplicate(nums []int) bool {
seen := make(map[int]struct{})
for _, x := range nums {
if _, ok := seen[x]; ok {
return true
}
seen[x] = struct{}{}
}
return false
}
import java.util.*;
public class Solution {
public boolean containsDuplicate(List<Integer> nums) {
Set<Integer> set = new HashSet<>();
for (int x : nums) {
if (set.contains(x)) {
return true;
}
set.add(x);
}
return false;
}
}
from typing import *
def contains_duplicate(nums: List[int]) -> bool:
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
export function containsDuplicate(nums) {
const seen = new Set();
for (const x of nums) {
if (seen.has(x)) {
return true;
}
seen.add(x);
}
return false;
}