`
Vitas_Wang
  • 浏览: 9792 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

find the majority element

 
阅读更多
this is a question from 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.

If you want to get the best solution, then you must analyst and make use of all the information provided in the problem.

question analysis:
the key hint is that the majority element always exist. So that means that the count of majority element is great than the count of all other element, so the
count(majority) - count(others) > 0.

below is the best solution:
public int majorityElement(int[] nums) {
        int result = nums[0];
        int count = 1;
        for(int i = 1; i < nums.length; i++){
            if(result == nums[i]){
                count++;
            }else{
                count--;
            }
            if(count == 0){
                result = nums[i];
                count++;
            }
        }
        return result;
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics