这周做的还是分治算法的题目
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.
也是比较经典的,求一个数组中出现次数超过一半的数字。
参考了一个寻找发帖水王问题的帖子发帖水王
这个问题也主要思想也是以大化小,因为我们要找的数字在整个数组中出现次数超过一半,那么很容易得到,如果删去两个数字(不同时为我们要找的那个数字)时,这个数字出现的次数仍然是整个数组的一半。
所以方法就是,从第一个数字开始计算,记录其出现的次数,如果它后面一个数字和它不同,那么把次数归零,再从下一个数字开始计算,这样就相当于删去了前两个数字,成功地以大化小。
int majorityElement(vector<int>& nums) {
int n, ntimes;
n = nums[0];
ntimes = 1;
for(int i = 1; i < nums.size(); i++) {
if (n == nums[i]) {
ntimes++;
} else {
if (ntimes = 0) {
n = nums[i];
ntimes = 1;
} else {
ntimes--;
}
}
}
return n;
}
本文介绍了一种寻找数组中出现次数超过一半的元素的有效算法。通过遍历数组并利用抵消思想,该算法能在O(n)时间内找到多数元素。
591

被折叠的 条评论
为什么被折叠?



