我试图使用Java 8重写Moore的投票算法的实现,以找到数组中的多数元素.
Java 7实现将是这样的:
public int findCandidate(int[] nums) {
int maj_index = 0, count = 1;
for(int i=1; i<nums.length;i++){
if(count==0){
count++;
maj_index=i;
}else if(nums[maj_index]==nums[i]){
count++;
} else {
count--;
}
}
return nums[maj_index];
}
Run Code Online (Sandbox Code Playgroud)
我能想到的方法是使用stream reduce来获得最终结果
public int findCandidate(int[] nums) {
int count = 1;
Arrays
.asList(nums)
.stream()
.reduce(0, (result, cur) -> {
if (count == 0) {
result = cur;
count++;
} else if (result == cur){
count++;
} else {
count --;
}
});
return result; …Run Code Online (Sandbox Code Playgroud)