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

思路:
1.Map計數,時間複雜度O(3n)
2.排序後取中值,時間複雜度依賴於排序算法,平均最快O(n*logn) –>時間效率不好,排除
3.count計數,時間複雜度O(n)

/* 法一:時間複雜度O(n)+空間複雜度O(n) */
import java.util.Map;
import java.util.HashMap;
public class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0;i < nums.length;i++) {
            map.put(nums[i], 0);
        }
        for (int i = 0;i < nums.length;i++) {
            map.put(nums[i], map.get(nums[i]) + 1);
        }
        int majority = nums[0];
        for (int i = 0;i < nums.length;i++) {
            if (map.get(majority) < map.get(nums[i])) {
                majority = nums[i];
            }
        }
        return majority;
    }
}

/* 優化目前最優解 */
/* 法一:時間複雜度O(n)+空間複雜度O(1) */
import java.util.Map;
import java.util.HashMap;
public class Solution {
    public int majorityElement(int[] nums) {
        int majority = nums[0];
        int count = 1;
        for (int i = 1;i < nums.length;i++) {
            if (count == 0) {
                majority = nums[i];
                count = 1;
            }
            else if (nums[i] == majority) count++;
            else count--;
        }
        return majority;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章