【Divide and Conquer】169. Majority Element(easy)
阿新 • • 發佈:2017-09-08
比較 esc time ble nbsp 也有 assume ray more
#Week_1#
#From LeetCode#
Description:
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.
Analysis:
這一題是在分治類型底下的一道easy題目,但是讀了題目之後,我第一感覺想到的就是直接掃描存下各個數的計數,然後再找到那個計數超過n/2的majority element。
如果先直接掃描後尋找majority element,則時間復雜度為O(n),總的來說還是比較快的,題目沒有給出n的規模,不過還可以繼續在這個方法的基礎上剪一下支。
在掃描的時候直接判斷元素的計數是否大於n/2,如果是則直接得到了,這樣就更快了。
題目類型是分治,我覺得這個題目用分治太過大材小用了,有點麻煩。
不過看到了discussion裏面有各種方法的解答,感覺很不錯,裏面也有分治的思想,大家可以參考參考。
鏈接:https://leetcode.com/problems/majority-element/discuss/
Code:
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 map<int, int> countOfNum; 5 int size = nums.size(); 6 for (int i = 0; i < size; i++) { 7 if (++countOfNum[nums[i]] > (size / 2)) return nums[i]; 8 } 9 } 10 };
run time:23ms
【Divide and Conquer】169. Majority Element(easy)