首页 > 其他 > 详细

LeetCode # Array # Easy # 169. Majority Element

时间:2018-05-05 14:04:31      阅读:221      评论: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.

题目:找出出现次数超过一半的元素。假设数组中一定有该元素。

思路:参考A Linear Time Majority Vote Algorithm,算法的简单演示:演示链接

算法的基本思路为:

  设置一个当前候选者,表示当前便遍历过的元素中的最多数。设置一个count,初始值为0,记录候选者比所有其他元素多出几个。

    当count= 0,将下一个元素设置为候选者,然后count+1;

  当count不等于0,如果下一个元素=候选者,则count+1,否则count-1。

  遍历结束后,候选者即为出现次数超过一半的元素。代码如下:

 1 class Solution {
 2     public int majorityElement(int[] nums) {
 3         int count = 0;
 4         int candidate = 0;
 5         for(int i = 0; i < nums.length; ++i){
 6           if(count == 0){
 7              candidate = nums[i];  
 8           }         
 9           if(candidate == nums[i])
10            ++count;
11          else
12             --count;
13         }
14         return candidate;
15     }
16 }

参考:https://www.cnblogs.com/JimmyTY/p/5020871.html

LeetCode # Array # Easy # 169. Majority Element

原文:https://www.cnblogs.com/DongPingAn/p/8994489.html

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