Offer to prove safety twenty-eight:

Casual working

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.

Thinking

Start time is very simple idea is to use a for loop, take a time into the first data cycle, then use a while loop, the number of times it appears plus one, and finally see who the number is greater than the value of the array half the length of the code is as follows:

 int m=array.length;
        int n=m/2;
        int i;
        for(i=0;i<m;i++){
            int k=array[i];
            int j=0;
            int p=0;
            while(j<m)
            {
                if(array[j]==k)
                {
                    p++;
                }
                j++;
            }
            if(p>n)
             break;
        }
        if(i==m)
            return 0;
        else
        return 
            array[i];

Thinking is the beginning, not too much thinking, write blog again found the time to use the map This question set is the most simple method, time complexity is O (N), mainly using the characteristic map collection. Personally I feel that for the calculation of digital map collection is still a great advantage.

Code

import java.util.*;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int len=array.length;
        int half=len/2;
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<len;i++){
            map.put(array[i],map.containsKey(array[i])? map.get(array[i])+1:1);
        }
        for(int i=0;i<len;i++){
            if(map.get(array[i])>half){
                return array[i];
            }
        }
        return 0;
    }
}
Published 49 original articles · won praise 29 · views 2933

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105374780