1133. Largest Unique Number

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

Вам Дан 정수 배열 nums, return наибольшее 정수, которое встречается только один раз. Если ни одно 정수 не встречается один раз, return -1.

예제:

Input: nums = [5,7,3,9,4,9,8,3,1]

Output: 8

Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it is the answer.

C# 해법

매칭됨/원본
public class Solution {
    public int LargestUniqueNumber(int[] nums) {
        Dictionary<int, int> count = new Dictionary<int, int>();
        
        foreach (int num in nums) {
            if (count.ContainsKey(num)) {
                count[num]++;
            } else {
                count[num] = 1;
            }
        }
        
        int result = -1;
        foreach (var entry in count) {
            if (entry.Value == 1) {
                result = Math.Max(result, entry.Key);
            }
        }
        
        return result;
    }
}

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 LargestUniqueNumber(vector<int>& nums) {
        unordered_map<int, int> count = new unordered_map<int, int>();
        
        foreach (int num in nums) {
            if (count.count(num)) {
                count[num]++;
            } else {
                count[num] = 1;
            }
        }
        
        int result = -1;
        foreach (var entry in count) {
            if (entry.Value == 1) {
                result = max(result, entry.Key);
            }
        }
        
        return result;
    }
}

Java 해법

매칭됨/원본
class Solution {
public int largestUniqueNumber(int[] A) {
        Map<Integer, Integer> count = new HashMap<Integer, Integer>();
        for (int i : A) {
          count.put(i, count.getOrDefault(i, 0) + 1);
        }
        int result = -1;
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            if (entry.getValue() == 1) {
              result = Math.max(result, entry.getKey());
            }
        }
        return result;
    }
}

Algorithm

Создайте хеш-таблицу для хранения количества каждого числа в 배열е.

Пройдите по 배열у и заполните хеш-таблицу количеством каждого числа.

Инициализируйте результат значением -1. Пройдите по хеш-таблице и если значение ключа равно 1, установите результат равным максимальному значению между ключом и текущим результатом. return результат.

😎

Vacancies for this task

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

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