169. Majority Element

作者: 番茄晓蛋 | 来源:发表于2017-06-12 15:47 被阅读7次

**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;
    }
}

相关文章

网友评论

    本文标题:169. Majority Element

    本文链接:https://www.haomeiwen.com/subject/lrblqxtx.html