LeetCode 169. Majority Element

原创 2018年03月07日 09:40:05

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.

解法:三国杀理论,假设各方(除了大于n/2的数以外的各种不同的数)群起攻击我方(大于n/2的数),就算我们忽略各方的内战,那么最后剩下的一定还是我。如果不忽略对方的内战则会剩下更多的我方,因此,我们每次遇到新的数字,就将原来的减一,或者前者减到0就换数值为新的数字。等到iterate完数组,得到的结果数字一定是majority element.
    public int majorityElement(int[] nums) {
        if (nums.length == 1) return nums[0];
        int num = nums[0];
        int count = 1;
        for (int i =1; i < nums.length; i++) {
            if (nums[i] == num) {
                count++;
            } else {
                count--;
                if (count == 0) {
                    num = nums[i];
                    count = 1;
                }
            }
        }
        return num;
    }

169. Majority Element [easy] (Python)

题目链接https://leetcode.com/problems/majority-element/题目原文 Given an array of size n, find the majorit...
  • coder_orz
  • coder_orz
  • 2016-05-14 20:04:32
  • 1627

【LeetCode-面试算法经典-Java实现】【169-Majority Element(主元素)】

【169-Majority Element(主元素)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-Jun-Chao】原...
  • DERRANTCM
  • DERRANTCM
  • 2015-08-23 06:38:30
  • 4908

[leetcode-169]Majority Element(java)

问题描述: Given an array of size n, find the majority element. The majority element is the element that...
  • zdavb
  • zdavb
  • 2015-08-23 11:05:36
  • 792

LeetCode169:Majority Element

Given an array of size n, find the majority element. The majority element is the element that appear...
  • u012501459
  • u012501459
  • 2015-07-09 19:29:49
  • 1823

LeetCode169——Majority Element

Given an array of size n, find the majority element. The majority element is the element that appear...
  • booirror
  • booirror
  • 2015-01-15 11:11:26
  • 6457

LeetCode169. Majority Element分治法

题意:求一个序列中出现次数多于一半的元素。 方法很多,可以排序、哈希表、分治等等。...
  • wmdshhz0404
  • wmdshhz0404
  • 2016-09-21 00:07:18
  • 723

169. Majority Element 难度:Easy 类别:分治

题目: Given an array of size n, find the majority element. The majority element is the element th...
  • luoyingmin
  • luoyingmin
  • 2016-09-11 11:06:16
  • 685

【分治算法】Leetcode编程题解:169. Majority Element Add to List

题目: Given an array of size n, find the majority element. The majority element is the element that a...
  • w_t_youxi
  • w_t_youxi
  • 2017-03-14 00:15:38
  • 287

LeetCode 169. Majority Element 题解(C++)

Given an array of size n, find the majority element. The majority element is the element that appear...
  • prayyojay
  • prayyojay
  • 2016-10-19 14:41:46
  • 331
收藏助手
不良信息举报
您举报文章:LeetCode 169. Majority Element
举报原因:
原因补充:

(最多只允许输入30个字)