题目:
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.
题意:就是给你一个Array,然后求其中最大的元素。所谓最大的元素也就是指其中出现次数大于 ⌊ n/2 ⌋的数。
此题是一道非常经典的题目,首先我们采用O(n)的时间复杂度来做,采用一个num来统计出现majority的元素,然后用一个count来统计次数。这里是这样来分析的,当我们遍历到下一个数字的时候,如果这个数字和之前我们保存的那个num一样,那么就将次数加1,否则就减1;如果发现次数为0,那么就将num值重新设置为新的majority值,然后将次数置为1,直到一次遍历结束。但是这种方法存在一个问题,就是最后存在的那个数不一定就是出现比一半还要多的数字,我们需要重新遍历一遍数组,用刚才得到的那个数字去计算到底在这个数组中存在有多少个刚才保存的那个数字,如果确实发现比一半还要多的,那么就将这个结果输出,否则就不是。所以这里是陷阱。
public int majorityElement(int[] nums)
{
int length = nums.length;
if(length <= 0)
return 0;
if(length == 1)
return nums[0];
int num = nums[0];
int count = 1;
for(int i = 1; i < length; i++)
{
if(nums[i] == num)
count++;
else
count--;
if(count == 0)
{
num = nums[i];
count++;
}
}
/*count= 0;
for(int j = 0; j < length; j++)
{
if(nums[j] == num)
count++;
}*/ //因为题目中说了,一定保证marjorityElement一定存在,所以不需要判断,但是严格来说,是需要判断的
return num;
}