题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
就问有没有更拉胯的代码解法,挑战下限,1%+1%
import java.util.HashSet;
import java.util.ArrayList;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
//先遍历一遍得到数字种类,用set做判定
HashSet type_set=new HashSet();
ArrayList type=new ArrayList();
for(Integer x:array){
if(type_set.add(x)){
type.add(x);
}
}
//再开一个与种类等长的数组,索引匹配,记录出现次数
ArrayList num=new ArrayList();
for (int i = 0; i <type.size() ; i++) {
num.add(0);
}
//再遍历一次种类数组,得到次数数组
for (int i = 0; i <type.size(); i++) {
for (int j = 0; j < array.length; j++) {
if(array[j]==type.get(i)){
num.set(i,num.get(i)+1);
}
}
}
//遍历次数数组,取出最大次数对应索引
int max=0;
int type_index = 0;
int most_type = 0;
for (int i = 0; i <num.size() ; i++) {
if(num.get(i)>=max){
max=num.get(i);
type_index=i;
}
}
//判定次数是否大于原数组长度一半,大则返回该索引对应的种类
if (max>array.length/2){
most_type=type.get(type_index);
}
return most_type;
}
}
曼迪匹艾公司福利 95人发布