首页 > 代码库 > 输出超过一半的数

输出超过一半的数

//输出超过一半的数,如果没有则输出-1。通过编译,bymyself
import java.util.*;
public class MoreThanHalf{
    public static void main(String args[]){
        int array[]={3,4,5,3,2,3};
        System.out.println(moreThanHalf(array));
    }
    public static int moreThanHalf(int[] array){
        Arrays.sort(array);
        Set sets = new TreeSet();
        List lists = new ArrayList();
        for(int i=0; i<array.length; i++){
            sets.add(String.valueOf(array[i]));//String.valueOf!!!
            lists.add(String.valueOf(array[i]));
        }
        //转为字符串,才能使用indexOf
        StringBuffer sb = new StringBuffer();
        Iterator it = lists.iterator();
        while(it.hasNext()){
            String s = (String)it.next();
            sb.append(s);        
        }
        String ss=sb.toString();
        //
        it = sets.iterator();
        while(it.hasNext()){
            String s = (String)it.next();
            int start = ss.indexOf(s);
            int end = ss.lastIndexOf(s);
            if(end-start+1>array.length/2){
                return Integer.parseInt(s);
            }
        }
        return -1;
    }
}

    

 

//输出超过一半的数,如果没有则输出-1。通过测试
import java.util.*;
public class MoreThanHalf1{
    public static void main(String args[]){
        int array[]={3,4,5,3,2,3};
        System.out.println(moreThanHalf(array));
    }
    public static int moreThanHalf(int[] array){
        if(array.length==1){//当数组中只有一个数时,要输出该数
            return array[0];
        }
        Arrays.sort(array);
        int count = 1;
        for(int i=0; i<array.length-1; i++){
            if(array[i]==array[i+1]){
                count++;
                if(count>array.length/2){//不是else if
                return array[i];
                }
            }else{
                count = 1;
            }
        }
        return -1;
    }
}