More than half of the number of figures appear to prove safety of the array 28. The time efficiency

Title Description

There are a number of array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output .
 
Problem-solving ideas
With Map <Integer, Integer>, key to digital, value is the number of the number that appears
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 
 * @author Transkai
 *
 */
public class MoreThanHalfNum_Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
         if (array.length==1) {
            return array[0];
        }
         Map<Integer, Integer> map=new HashMap<>();
         boolean flag=true;
         for(int i=0;i<array.length;i++) {
            for (Entry<Integer, Integer> map2:map.entrySet()) {
                if (array[i]==map2.getKey()) {
                    map.put(array[i], map.get(array[i])+1);    
                    flag=false;
                    if (map.get(array[i])>array.length/2) {
                        return array[i];
                    }
                }
                
            }
            if (flag) {
                map.put(array[i], 1);
            }
            
         }

         return 0;
            
        }
     public static void main(String[] args) {
         MoreThanHalfNum_Solution moreThanHalfNum_Solution=new MoreThanHalfNum_Solution();
         int[] array=new int[]{1,2,3,2,2,2,5,4,2};
         int a=moreThanHalfNum_Solution.MoreThanHalfNum_Solution(array);
         System.out.println(a);
    }
}

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11266406.html