首页 > 其他 > 详细

leetcode 169.Majority Element

时间:2015-03-02 18:38:30      阅读:92      评论:0      收藏:0      [点我收藏+]

题目:

  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.

 

解决方案:Runtime: 229 ms

public class Solution {
    //学习网上方法,每找出两个不同的,则成对删除,最后剩余的就是所求元素
    public int majorityElement(int[] num) {
        int count = 0;
        int maj = 0;
        for(int i = 0; i < num.length; i++){
            if(count == 0){
                maj = num[i];
                count++;
            }else{
                if(maj == num[i]){
                    count ++;
                    if(count > num.length/2)
                        return maj;
                }else{
                    count --;
                }
            }
        }
        return maj;
    }
}

 

总结:这个方法是我从网上看到的,也是大部分人的做法,刚开始做没想到这个方法,还想着用数组去做,但是那样太复杂了。这个方法值得学习。

leetcode 169.Majority Element

原文:http://www.cnblogs.com/Pillar/p/4309065.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!