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

[leetcode]Majority Element

时间:2015-08-14 13:51:04      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:leetcode

原题

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

思路

This problem is required to get the majority element appeard. As it appears more than [n/2] times. So we can compare two elements, if they do not have the same value, we can delete them. And at last, the only left element must be the one we want to get.  The time complexity is O(n)

代码

int majorityElement(int* nums, int numsSize) {
    int element = 0;
    int count = 0;
 
    for(int i = 0; i < numsSize; i++)
    {
        if(count == 0)
        {
           element = nums[i];
           count++;
        }else
        {
            if(element == nums[i])
            {
                count++;
            }else
            {
                count--;
            }
       }
    }
    return element;
}

运行结果

42 / 42 test cases passed.
Status:

Accepted

Runtime: 8 ms
Submitted: 10 minutes ago

版权声明:本文为博主原创文章,未经博主允许不得转载。

[leetcode]Majority Element

标签:leetcode

原文地址:http://blog.csdn.net/u011960402/article/details/47659797

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