169. Majority Element
創(chuàng)新互聯(lián)公司長(zhǎng)期為1000多家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為海晏企業(yè)提供專業(yè)的網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè),海晏網(wǎng)站改版等技術(shù)服務(wù)。擁有十載豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。
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來(lái)處理。
class Solution { public: int majorityElement(vector& nums) { map record; for (int i = 0; i < nums.size(); i++) { if (record.find(nums[i]) == record.end()) { record.insert(pair (nums[i], 1)); if (record[nums[i]] > nums.size() / 2) { return nums[i]; } } else { record[nums[i]] += 1; if (record[nums[i]] > nums.size() / 2) { return nums[i]; } } } return 0; } };
思路2:
采用雙循環(huán)
int majorityElement(vector& nums) { int hit = 0; int currentElem; for (int i = 0; i < nums.size(); i++) { currentElem = nums[i]; hit = 0; for (int j = 0; j < nums.size(); j++) { if (nums[j] == currentElem) { hit++; if (hit > nums.size() / 2) { return currentElem; } } } } return 0; }
2016-08-10 12:19:37