问题描述:
我的原始代码:
class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1) return nums[0];
for (int i=0;i<=nums.length/2;i++)
{ int s=1;
for(int j=i+1;j<nums.length;j++)
{
if(nums[j]==nums[i]) s++;
if(s>=(nums.length+1)/2)
{
return nums[j];
}
}
}
return -1;
}
}
时间复杂度为O(n)
如何使时间复杂度为O(1)呢
这里就要用到投票算法,代码如下:
class Solution {
public int majorityElement(int[] nums) {
int taotal = 1;
int people= nums[0];
for(int i = 1;i<nums.length;i++){
if(people!=nums[i]){
taotal--;
}else{
taotal++;
}
if(taotal<0){
people = nums[i];
taotal = 1;
}
}
return taotal>0?people:-1;
}
}