# Leetcode [No. 169] Majority Element(EASY) ## 題目 https://leetcode.com/problems/majority-element/ ## 思路 + 這個題目因為保證最多的數字會出現n/2次,所以只要用hashMap記錄每個出現的值,並且在判斷完後馬上return即可 ```c++= class Solution { public: int majorityElement(vector<int>& nums) { int max_appears = floor(nums.size()/2); unordered_map<int,int> hashMap; for(int i = 0 ;i <nums.size(); i++) { hashMap[nums[i]]++; if(hashMap[nums[i]]>max_appears) { return nums[i]; } } return -1; } }; ``` ### 解法分析 + time complexity: O(n) ### 執行結果  ## follow up: > use linear time and O(1) space ```C++= ``` ### 解法分析 ### 執行結果
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up