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


解题思路:

方法一: 用Array.sort , 排序后看有没有连续的数长度大于n/2。 Complexity is O(nlgn)

            改进方法: 若是长度大于n/2, 那么array 正中间的值就是要找的数。

方法二: “投票算法” 这种算法复杂度低。

设定两个变量candidate和count。candidate保存当前可能的候选众数,count保存该候选众数的出现次数。

遍历数组num。

如果当前的数字e与候选众数candidate相同,则将计数count + 1

否则,如果当前的候选众数candidate为空,或者count为0,则将候选众数candidate的值置为e,并将计数count置为1。

否则,将计数count - 1

最终留下的候选众数candidate即为最终答案。

以上算法时间复杂度为O(n),空间复杂度为O(1)


Java code:

方法一:

 public int majorityElement(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        Arrays.sort(nums);
        
        int prev = nums[0];
        int count = 1;
        for(int i = 1; i< nums.length; i++){
            if(nums[i] == prev){
                count++;
                if(count > nums.length/2) {
                    return prev;
                }
            }else {
                count = 1;
                prev = nums[i];
            }
        }
        return 0;
    }

public int majorityElement(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        Arrays.sort(nums);
        return nums[nums.length/2];
    }

方法二:

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

Reference:

1. http://www.programcreek.com/2014/02/leetcode-majority-element-java/

2. http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/

原文地址:https://www.cnblogs.com/anne-vista/p/4856612.html