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] Post Views: 10