1150. Check If a Number Is Majority Element in a Sorted Array

LeetCode easy original: C# #array #csharp #easy #leetcode #sort
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

Дан entero arreglo nums, sorted в неубывающем порядке, и entero target. return true, если target является elementом большинства, или false в противном случае.

element большинства в arregloе nums — это element, который встречается в arregloе более чем nums.length / 2 раз.

Ejemplo:

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# solución

coincidente/original
public 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++ solución

borrador automático, revisar antes de enviar
#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 solución

coincidente/original
class 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 solución

coincidente/original
class 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) // 2

Go solución

coincidente/original
package main

func isMajorityElement(nums []int, target int) bool {
    count := 0
    for _, num := range nums {
        if num == target {
            count++
        }
    }
    return count > len(nums)/2
}

Algorithm

1⃣Инициализация переменной count:

Инициализируйте переменную count значением 0..

2⃣Итерация по списку nums:

Пройдите по каждому elementу списка nums.

Если element num равен target, увеличьте значение переменной count.

3⃣Проверка условия мажоритарного elementа:

Если count больше чем половина длины списка nums, return true.

В противном случае return false.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.