照着题解自己写的,能通过部分用例,搜了下ds是局域变量的问题,他这种方法很取巧用了投票算法,我没听过,这里记录一下他的算法。
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for (int num : nums){
if(votes==0){
x=num;
if(num==x){
votes++;
}else{
votes--;
}
}
}
return x;
}
}
他的算法:
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for (int num : nums){
if (votes == 0) x = num;
votes += num == x ? 1 : -1;
}
return x;
}
}