169. Majority Element

**Description**Hints**Submissions**Solutions

Total Accepted: 192332
Total Submissions: 417285
Difficulty: Easy
Contributor: LeetCode

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.
Credits:Special thanks to @ts for adding this problem and creating all test cases.

Hide Company Tags
Adobe Zenefits
Hide Tags
Array Divide and Conquer Bit Manipulation
Hide Similar Problems
(M) Majority Element II

public class Solution {
    // O(n) time O(1) space fastest solution
    public int majorityElement(int[] nums) {
        int major = nums[0], count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                count++;
                major = nums[i];
            } else if (major == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return major;
    }
    
    public int majorityElementFailed(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int n : nums) {
            set.add(n);
        }
        int max = -1;
        
        int[] countList = new int[nums.length];
        
        for (int k : set) {
           for (int i = 0; i < nums.length; i++) {
               if (nums[i] == k) countList[i]++;
           }
        }
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容