题意:找出数组中出现次数大于等于一半的数字
解法:用两个变量,cur_num当前出现次数最多的数字,times记录cur_num出现的次数,当num[i]与cur_num相同则times+1,否则times-1,如果times<0,怎更改cur_num和times
复杂度:时间O(n)
空间O(1)
public class Solution {
public int majorityElement(int[] num) {
int times = 0;
int cur_num = num[0];
int n = num.length;
for(int i=1;i<n;i++)
{
if(num[i] == cur_num)
{
times+=1;
}
else
{
times--;
if(times<0)
{
cur_num = num[i];
times = 0;
}
}
}
return cur_num;
}
}