(5/31/16)Leetcode 169. Majority Element

Easy, 用时3分钟
解法一:
算法名称为Boyer–Moore majority vote algorithm

  1. Eliminate all elements except one.
    Iterating through the array of numbers, maintain a current candidate and a counter initialized to 0. With the current element x in iteration, update the counter and (possibly) the candidate:
    If the counter is 0, set the current candidate to x and the counter to 1. If the counter is not 0, increment or decrement the counter based on whether x is the current candidate.
  2. Determine if the remaining element is a valid majority element.
    With the candidate acquired in step 1, iterate through the array of numbers and count its occurrences. Determine if the result is more than half of the sequence's length. If so, the candidate is the majority. Otherwise, the sequence doesn't contain a majority.
public class Solution {
    public int majorityElement(int[] nums) {
        if(nums.length == 0) return -1;
        int res = nums[0];
        int count = 0;
        for (int i = 0;i < nums.length; i++){
            if (res == nums[i]) count ++;
            else {
                if (count > 0) count --;
                else res = nums[i];
            }
        }
        return res;
    }
}

解法二:
排序取中间值

你可能感兴趣的:((5/31/16)Leetcode 169. Majority Element)