Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Majority Element

Posted on August 1, 2018July 26, 2020 by braindenny

More than half elements are the same. Identify it fast



Similar Problems:

  • LeetCode: Check If a Number Is Majority Element in a Sorted Array
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #moorevoting, #array, #classic

Given an array of size n, find the majority element. The majority element is the element that appears more than n/2 times.

You may assume that the array is non-empty and the majority element always exist in the array.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/majority-element
// Basic Ideas: morevoting
//
// For two different values, collision these two
//
// Complexity: Time O(n), Space O(1)
func majorityElement(nums []int) int {
    v, cnt := nums[0], 1
    for i:=1; i<len(nums); i++ {
        if nums[i] == v { 
            cnt++ 
        } else {
            cnt--
            if cnt == 0 {
                i++
                v, cnt = nums[i], 1
            }
        }
    }
    return v
}
## https://code.dennyzhang.com/majority-element
class Solution(object):
    def majorityElement1(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ## Ideas: sort, then find the middle item
        ## Complexity: Time O(n*log(n)), Space O(1)
        length = len(nums)
        nums2 = sorted(nums)
        return nums2[(length-1)/2]
linkedin
github
slack

Post Views: 10
Posted in HardTagged #classic, #moorevoting

Post navigation

LeetCode: Add Two Numbers
Series: TwoSum Problems & Follow-Up

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.