LeetCode 169. Majority Element

时间:2024-08-27 17:34:32

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;
     }
 }