首页 > 其他 > 详细

【LeetCode】169. Majority Element

时间:2017-07-30 16:53:01      阅读:182      评论:0      收藏:0      [点我收藏+]

原题链接: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];  
    }  
}; 

第二个方法代码量相对较少,容易想到,不过我比较了一下运行时间,还是第一个方法的时间少。

【LeetCode】169. Majority Element

原文:http://www.cnblogs.com/jialei-bupt/p/7259400.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!