IT常识
技术 Python PHP JavaScript IOS Android Java 数据库 资源 公众号 代码片段 github
  • IT常识
  • 技术

Lintcode 166. 主元素

Posted 2020-08-26

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode 166. 主元素相关的知识,希望对你有一定的参考价值。

-----------------------------------

Moore\'s voting algorithm算法:从一个集合中找出出现次数半数以上的元素,每次从集合中去掉一对不同的数,当剩下一个元素的时候(事实上只要满足一个元素出现过半就一定会剩下一个元素的)这个元素就是我们要找的数了。

 

 AC代码:

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        int e, count;
        e=count=0;
        for(int i=0;i<nums.size();i++){
            if(count==0){
                e=nums.get(i);
                count++;
            }else{
                if(e==nums.get(i)){
                    count++;
                }else{
                    count--;
                }
            }
        }
        return e;
    }
}

 

 

题目来源: http://www.lintcode.com/zh-cn/problem/majority-number/

参考资料: http://blog.csdn.net/chfe007/article/details/42919017

 

以上是关于Lintcode 166. 主元素的主要内容,如果未能解决你的问题,请参考以下文章

LintCode之主元素

lintcode 主元素解决方法

LintCode 166. 链表倒数第n个节点

lintcode_46.主元素

lintcode.46 主元素

166 链表倒数第n个结点

(c)2006-2024 SYSTEM All Rights Reserved IT常识