645. Set Mismatch

LeetCode easy original: C# #array #csharp #easy #hash-table #leetcode #search
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

У вас есть набор целых чисел s, который изначально содержит все числа от 1 до n. К сожалению, из-за какой-то ошибки одно из чисел в s продублировалось в другое number в наборе, что привело к повторению одного числа и потере другого. Вам дан 정수 배열 nums, представляющий состояние данных в этом наборе после ошибки. find number, которое встречается дважды, и number, которое отсутствует, и return их в виде 배열а.

예제:

Input: nums = [1,2,2,4]

Output: [2,3]

C# 해법

매칭됨/원본
public class Solution {
    public int[] FindErrorNums(int[] nums) {
        int n = nums.Length;
        HashSet<int> numSet = new HashSet<int>();
        int duplicate = -1;
        foreach (int num in nums) {
            if (!numSet.Add(num)) {
                duplicate = num;
            }
        }
        int missing = (n * (n + 1)) / 2 - numSet.Sum();
        return new int[] { duplicate, missing };
    }
}

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 vector<int>& FindErrorNums(vector<int>& nums) {
        int n = nums.size();
        HashSet<int> numSet = new HashSet<int>();
        int duplicate = -1;
        foreach (int num in nums) {
            if (!numSet.push_back(num)) {
                duplicate = num;
            }
        }
        int missing = (n * (n + 1)) / 2 - numSet.Sum();
        return new int[] { duplicate, missing };
    }
}

Java 해법

매칭됨/원본
class Solution {
    public int[] findErrorNums(int[] nums) {
        int n = nums.length;
        Set<Integer> numSet = new HashSet<>();
        int duplicate = -1;
        for (int num : nums) {
            if (!numSet.add(num)) {
                duplicate = num;
            }
        }
        int missing = (n * (n + 1)) / 2 - numSet.stream().mapToInt(Integer::intValue).sum();
        return new int[]{duplicate, missing};
    }
}

JavaScript 해법

매칭됨/원본
var findErrorNums = function(nums) {
    let numSet = new Set();
    let duplicate = -1;
    const n = nums.length;
    for (let num of nums) {
        if (numSet.has(num)) {
            duplicate = num;
        }
        numSet.add(num);
    }
    let missing = (n * (n + 1)) / 2 - [...numSet].reduce((a, b) => a + b, 0);
    return [duplicate, missing];
};

Python 해법

매칭됨/원본
def findErrorNums(nums):
    n = len(nums)
    num_set = set()
    duplicate = -1
    for num in nums:
        if num in num_set:
            duplicate = num
        num_set.add(num)
    missing = (n * (n + 1)) // 2 - sum(num_set)
    return [duplicate, missing]

Go 해법

매칭됨/원본
func findErrorNums(nums []int) []int {
    numSet := make(map[int]bool)
    duplicate := -1
    n := len(nums)
    for _, num := range nums {
        if numSet[num] {
            duplicate = num
        }
        numSet[num] = true
    }
    sum := 0
    for num := range numSet {
        sum += num
    }
    missing := (n * (n + 1)) / 2 - sum
    return []int{duplicate, missing}
}

Algorithm

Пройдите по 배열у, используя набор для отслеживания чисел, чтобы определить дублированное number.

Определите отсутствующее number, используя сумму чисел от 1 до n и текущую сумму 배열а.

return дублированное и отсутствующее числа в виде 배열а.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.