1150. Check If a Number Is Majority Element in a Sorted Array
leetcode easy
Task
Дан целочисленный массив nums, отсортированный в неубывающем порядке, и целое число target. Верните true, если target является элементом большинства, или false в противном случае.
Элемент большинства в массиве nums — это элемент, который встречается в массиве более чем nums.length / 2 раз.
Пример:
Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true
Explanation: The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.
C# solution
matched/originalpublic class Solution {
public bool IsMajorityElement(int[] nums, int target) {
int count = 0;
foreach (int num in nums) {
if (num == target) {
count++;
}
}
return count > nums.Length / 2;
}
}C++ solution
auto-draft, review before submit#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 bool IsMajorityElement(vector<int>& nums, int target) {
int count = 0;
foreach (int num in nums) {
if (num == target) {
count++;
}
}
return count > nums.size() / 2;
}
}Java solution
matched/originalclass Solution {
public boolean isMajorityElement(int[] nums, int target) {
int count = 0;
for (int num : nums) {
count = num == target ? count + 1 : count;
}
return count > nums.length / 2;
}
}Python solution
matched/originalclass Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
count = 0
for num in nums:
if num == target:
count += 1
return count > len(nums) // 2Go solution
matched/originalpackage main
func isMajorityElement(nums []int, target int) bool {
count := 0
for _, num := range nums {
if num == target {
count++
}
}
return count > len(nums)/2
}Explanation
Algorithm
1⃣Инициализация переменной count:
Инициализируйте переменную count значением 0..
2⃣Итерация по списку nums:
Пройдите по каждому элементу списка nums.
Если элемент num равен target, увеличьте значение переменной count.
3⃣Проверка условия мажоритарного элемента:
Если count больше чем половина длины списка nums, верните true.
В противном случае верните false.
😎