leetcode 169 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.

輸入一個大小爲n的數組,整個數組裏面將會含有一個衆數,即這個元素出現的次數大於n/2,咱們須要找到並返回這個衆數數組

思路

  • 這道題也是一道關於數組的重複元素的問題
  • 首先我想到的辦法是,使用HashMap實現,key是元素的值,value則是這個元素在當前出現的次數,一旦這個次數大於n/2,咱們就能夠中止咱們的遍歷
  • 但實際上,還有一種更簡單的方法。由於衆數出現的次數一定大於n/2,因此咱們只要取第n/2個位置上的元素,這個元素必定爲咱們要找的衆數。
  • 感謝@SegmentWarrior提供的解法三,不須要創建hashmap所產生的額外空間,同時時間複雜度爲O(n)

解法一 HashMap

//HashMap實現 時間複雜度O(n)
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
        int length = nums.length;
        if(length<=1){
            return nums[0];
        }
        for(int i=0;i<length;i++){
            if(count.get(nums[i]) != null){
                int temp = count.get(nums[i]);
                count.put(nums[i],temp+1);  
                if(temp+1 > length/2){
                    return nums[i];
                }
            }else{
                count.put(nums[i], 1);
            }

        }
        
        return -1;
    }

解法二 直接取n/2位置元素

//思想:對於一個排序好的數組,第n/2的位置的元素必定是存在的這個衆數
    public int majorityElement(int[] nums) {
        
        Arrays.sort(nums);
        return nums[nums.length/2];
    }

解法三 對出現次數計數

public int majorityElement(int[] nums) {
        int res = nums[0];
        int count = 1;
        
        for(int i=1;i<nums.length;i++){
            if(nums[i] == res) count ++;
            else if(count >1) count --;
            else res = nums[i];
        }
        return res;
    }
相關文章
相關標籤/搜索