LeetCode 169. Majority Element(Java)

题目:
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的元素,假设数组非空并且存在大多数元素。


思路:
多数投票算法:选出当前元素majority ,遍历数组nums,如果当前元素majority 与nums[i]相同则count++,否则count–。如果count出现小于0的情况,则majority=nums[i],最后majority即为所求元素。


代码:

public class Solution {
    public int majorityElement(int[] nums) {
        int majority = 0;
        int count = 0;
        for(int i = 0;i < nums.length;i++){
            if(count == 0){
                majority = nums[i];
            }
            if(nums[i] == majority){
                count++;
            }else{
                count--;
                if(count < 0){
                    majority = nums[i];
                }
            }
        }
        return majority;
    }
}

你可能感兴趣的:(LeetCode)