首页 > 其他 > 详细

[leetcode]Majority Element

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

原题

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

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

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