congr / world

2 stars 1 forks source link

LeetCode : 169. Majority Element #432

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/majority-element/

image

congr commented 5 years ago

Time : O(N), Space : O(N)

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap();

        for (int n : nums) {
            int cnt = map.merge(n, 1, Integer::sum);
            if (cnt > nums.length/2)
                return n;
        }

        return 0;
    }
}
congr commented 5 years ago

Shortest code

image

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}