1. 程式人生 > >169.Majority Element

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次

思路:看到這個題,想到以前一個題也是找出出現次數最的元素,不過那個是返回次數,這個是返回元素本身
所以這裡在查詢的過程中要記錄元素的值

我的解題過程為:首先將陣列排序,然後將記錄值Index與陣列中的元素進行比較,如果相同增加次數,如果不同減少次數,當記錄次數小於等於0的時候,更換記錄值index,
這種方法時間複雜度是O(nlogn),空間複雜度是O(1)。

當然這個題也可以試著用雜湊表解決,這種解法是使用一個hash表,鍵用來存放陣列的元素,鍵對應的值存放元素出現的次數。遍歷整個陣列,查詢它在hash表中是否出現,
如果出現將出現次數加1,如果沒有出現,將它插入hash表中,並設定它的出現次數為1。每次遍歷到一個元素,判斷它的出現次數是否超過了陣列長度的一半,
要是超過了就返回該元素。時間複雜度是O(n),空間複雜度是O(n)。。

public int majorityElement(int[] nums) {

        int len = nums.length;
        int max = 0;
        int index = nums[0];
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (max <= 0){
                index = nums[i];
            }
            if (nums[i] == index
){ max ++; }else { max --; } } return index;