169. Majority Element
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.
Дан 배열 nums размера n, return element большинства.
element большинства — это element, который встречается более чем ⌊n / 2⌋ раз. Можно предположить, что element большинства всегда существует в 배열е.
예제:
Input: nums = [3,2,3]
Output: 3
C# 해법
매칭됨/원본public class Solution {
private Dictionary<int, int> countNums(int[] nums) {
var counts = new Dictionary<int, int>();
foreach (int num in nums) {
if (!counts.ContainsKey(num)) {
counts.Add(num, 1);
} else {
counts[num]++;
}
}
return counts;
}
public int MajorityElement(int[] nums) {
var counts = countNums(nums);
foreach (var count in counts) {
if (count.Value > nums.Length / 2)
return count.Key;
}
return 0;
}
}
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:
private unordered_map<int, int> countNums(vector<int>& nums) {
var counts = new unordered_map<int, int>();
foreach (int num in nums) {
if (!counts.count(num)) {
counts.push_back(num, 1);
} else {
counts[num]++;
}
}
return counts;
}
public int MajorityElement(vector<int>& nums) {
var counts = countNums(nums);
foreach (var count in counts) {
if (count.Value > nums.size() / 2)
return count.Key;
}
return 0;
}
}
Java 해법
매칭됨/원본class Solution {
private Map<Integer, Integer> countNums(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (int num : nums) {
if (!counts.containsKey(num)) {
counts.put(num, 1);
} else {
counts.put(num, counts.get(num) + 1);
}
}
return counts;
}
public int majorityElement(int[] nums) {
Map<Integer, Integer> counts = countNums(nums);
Map.Entry<Integer, Integer> majorityEntry = null;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if (entry.getValue() > nums.length / 2) return entry.getKey();
}
return majorityEntry.getKey();
}
}
JavaScript 해법
매칭됨/원본var majorityElement = function (nums) {
let counts = {};
for (let num of nums) {
if (!counts[num]) {
counts[num] = 1;
} else {
counts[num]++;
}
}
for (let num in counts) {
if (counts[num] > nums.length / 2) return Number(num);
}
return 0;
};
Python 해법
매칭됨/원본class Solution:
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
Go 해법
매칭됨/원본func majorityElement(nums []int) int {
counts := make(map[int]int)
for _, num := range nums {
if _, ok := counts[num]; ok {
counts[num]++
} else {
counts[num] = 1
}
}
for num, count := range counts {
if count > len(nums)/2 {
return num
}
}
return 0
}
Algorithm
1️⃣
Использование HashMap для подсчета:
Создайте HashMap для отслеживания количества каждого elementа в 배열е.
2️⃣
Подсчет вхождений elementов:
Пройдите по 배열у nums, увеличивая счетчик в HashMap для каждого elementа.
3️⃣
Поиск elementа большинства:
Определите element большинства, просмотрев HashMap и найдя ключ с максимальным значением, которое должно быть больше ⌊n / 2⌋
😎
Vacancies for this task
활성 채용 with overlapping task tags are 표시됨.
아직 활성 채용이 없습니다.