LeetCode # Array # Easy # 169. Majority Element

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

猜你喜欢

转载自www.cnblogs.com/DongPingAn/p/8994489.html
今日推荐