码迷,mamicode.com
首页 > 其他好文 > 详细

169. Majority Element

时间:2017-09-23 17:22:45      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:appear   exist   return   一半   code   public   bsp   blog   appears   

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.

 

 

 数组中出现次数超过一半的数字

 

 

C++(19ms):

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int len = nums.size() ;
 5         int res = nums[0] ;
 6         int times = 1 ;
 7         for (int i = 1 ; i < len ; i++){
 8             if (times == 0){
 9                 res = nums[i] ;
10                 times = 1 ;
11             }else if (res == nums[i]){
12                 times++ ;
13             }else{
14                 times-- ;
15             }
16         }
17         times = 0 ;
18         for(int i = 0 ; i < len ; i++){
19             if (res == nums[i])
20                 times++ ;
21         }
22         if (times*2 <= len)
23             res = 0 ;
24         return res ;
25     }
26 };

 

169. Majority Element

标签:appear   exist   return   一半   code   public   bsp   blog   appears   

原文地址:http://www.cnblogs.com/-Buff-/p/7581584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!