又要表一表我有多low,这道题,腾讯,滴滴面试的时候都有。腾讯问后,看了几次如何解题,但是没想到滴滴面试时,却是得不到正确结果,那么我是怎么写的呢?
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int pivot =array[0];
for(int i=1,count=1;i<array.length;i++){
count=array[i]==pivot?count++:count--;
// 如果改成 int temp = array[i]==pivot?count++:count--; 就是正确的
if(count==0){
count=1;
pivot=array[i];
}
}
int count=0;
if(pivot!=array[0]){
for(int i=0;i<array.length;i++){
if(array[i]==pivot){
count++;
}
}
return count>array.length/2?pivot:0;
}else{
return array[0];
}
}
}
错误一:count=array[i]==pivot?count++:count--;
这种自增后面接一个自减,最后的效果就是,不增不减……
上面这个错误找的不对,这个不是自增后面接一个自减,而是给count赋值的问题
int count = 1;
count = count++;
赋值结束后 count 不会自增
错误二:for循环后,二次判断的逻辑错误,会造成的错误是在偶数个数组,第一个和第二个元素相等(假如是majority),且是数组长度一半的那个数字,此时应该返回0,按照代码逻辑是返回majority。
正确的代码是:
public static int moreThanHalfNum(int [] array) {
int pivot = array[0];
for (int i = 1, count = 1; i < array.length; i++) {
count = array[i] == pivot ? count + 1 : count - 1;
if (count == 0) {
count = 1;
pivot = array[i];
}
}
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == pivot)
count++;
return count > array.length / 2 ? pivot : 0;
}