【LeetCode】169. Majority Element
原題鏈接:https://leetcode.com/problems/majority-element/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.
想法:
1.比較普通的想法,有一個(gè)標(biāo)記,初始值為1,對(duì)應(yīng)一個(gè)計(jì)數(shù)初始值為1.
? ?遍歷數(shù)組,若數(shù)組值和標(biāo)記值相等,計(jì)數(shù)加一;否則計(jì)數(shù)減一,當(dāng)計(jì)數(shù)為0時(shí),更改標(biāo)記值為當(dāng)前數(shù)組值。代碼如下:
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 int res = nums[0]; 5 int count = 1; 6 for (int i = 1;i < nums.size(); ++i) { 7 if (res == nums[i]) count++; 8 else { 9 count--; 10 if (count == 0) { 11 res = nums[i]; 12 count = 1; 13 } 14 } 15 } 16 return res; 17 } 18 };2.首先將整個(gè)數(shù)組排序,由題意返回?cái)?shù)組中間值即可。代碼如下:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };第二個(gè)方法代碼量相對(duì)較少,容易想到,不過(guò)我比較了一下運(yùn)行時(shí)間,還是第一個(gè)方法的時(shí)間少。
轉(zhuǎn)載于:https://www.cnblogs.com/jialei-bupt/p/7259400.html
總結(jié)
以上是生活随笔為你收集整理的【LeetCode】169. Majority Element的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 百岁山矿泉水是哪国的品牌?
- 下一篇: 粽叶包的腊肉叫什么?