[leetcode]Majority Element

题目描述如下:

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.

很明显是应用了map,没有什么难点,一遍AC。代码如下:

public class Solution {
    public int majorityElement(int[] nums) {
       if(nums.length == 1) return nums[0];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int i, res = 0;
        for(i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i], map.get(nums[i]) + 1);
                if(map.get(nums[i]) > nums.length / 2){
                    res = nums[i];
                    break;
                }
            }else{
                map.put(nums[i], 1);
            }
        }
        return res;        
    }
}

题目链接:https://leetcode.com/problems/majority-element/

你可能感兴趣的:(LeetCode)