LeetCode 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.

分析:

遍历数组,每当发现一对儿不相同的element时就成对儿删除,最后剩下的一定是个数过半儿的element。

 public class Solution {
     public int majorityElement(int[] nums) {
         int count = 0;
         int majElem = 0;

         for(int i=0; i<nums.length; i++) {
             if(count == 0) {
                 majElem = nums[i];
                 count++;
             } else {
                 if(majElem == nums[i]) {
                     count++;
                 } else {
                     count--;
                 }
             }
         }

         return majElem;
     }
 }
上一篇:我的微信小程序入门踩坑之旅


下一篇:CentOS7使用tar.gz包安装MySql的踩坑之旅