【LeetCode】169. Majority Element
生活随笔
收集整理的這篇文章主要介紹了
【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.比較普通的想法,有一個標記,初始值為1,對應一個計數初始值為1.
? ?遍歷數組,若數組值和標記值相等,計數加一;否則計數減一,當計數為0時,更改標記值為當前數組值。代碼如下:
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.首先將整個數組排序,由題意返回數組中間值即可。代碼如下:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };第二個方法代碼量相對較少,容易想到,不過我比較了一下運行時間,還是第一個方法的時間少。
轉載于:https://www.cnblogs.com/jialei-bupt/p/7259400.html
總結
以上是生活随笔為你收集整理的【LeetCode】169. Majority Element的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百岁山矿泉水是哪国的品牌?
- 下一篇: 粽叶包的腊肉叫什么?