标签: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
原文地址:http://blog.csdn.net/u011960402/article/details/47659797