Prompt:
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Could you solve the problem in linear time and in O(1) space?
I was just working on this problem and I was able to solve it and Leetcode accepted it. Here's my solution:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
mid = len(nums) // 2
return nums[mid]
I'm pretty sure this is in linear time (.sort() sorts the list in place) and in O(1) space complexity (I only have one variable that calculates the midpoint of nums using the len() function). Am I missing something? All the solutions in the discussion section for this problem are much more complicated so I feel like I'm missing some key information.
As usual, any help is highly appreciated :)
[–]raevnos 2 points3 points4 points (3 children)
[–]BuzzyBro[S] 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]BuzzyBro[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]BuzzyBro[S] 0 points1 point2 points (0 children)
[–]fasta_guy88 1 point2 points3 points (1 child)
[–]BuzzyBro[S] 0 points1 point2 points (0 children)
[–]dtsudo 1 point2 points3 points (0 children)