日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】169. Majority Element

發(fā)布時(shí)間:2025/5/22 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】169. Majority Element 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

原題鏈接: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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。