More than half of the numbers to prove safety offer 28. arrays appear

More than half of the array 28. The numbers appear

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.

A thought:

Sorting an array to determine the middle of the repetition of elements if more than half the length of the array, if more than it is, or is not

. 1  Import java.util.Arrays;
 2  public  class Solution {
 . 3      public  int MoreThanHalfNum_Solution ( int [] Array) {
 . 4          IF (Array == null || be array.length == 0 ) {
 . 5              return  0 ;
 . 6          }
 . 7          // Sort 
. 8          Arrays.sort (Array);
 . 9          // number of elements of the statistical middle 
10          int Center = Array [be array.length / 2 ];
 . 11          int CNT = 0 ;
 12 is         for ( int I = 0 ; I <be array.length; I ++ ) {
 13 is              IF (Array [I] == Center) {
 14                  CNT ++ ;
 15              }
 16          }
 . 17           
18 is          // if more than half of the output, or do not exist 
. 19         return (CNT> be array.length / 2 ) Center:? 0 ;
 20 is      }
 21 is }

 

Thinking two: 

 The idea of using offensive and defensive positions:
the first digit as the first soldier defensive positions; count = 1;
 experiencing the same elements, count ++;
 encounter the same elements, that is the enemy, die, count--; when faced count is 0, again i value as the new defensive positions soldiers, continue to remain in the last position on the soldiers, there is likely to be the main element.
 Plus one cycle, the number of records to see if the soldier is greater than the general array can be.

 1 import java.util.Arrays;
 2 public class Solution {
 3     public int MoreThanHalfNum_Solution(int [] array) {
 4         if(array == null || array.length == 0){
 5             return 0;
 6         }
 7         int soldier = array[0];
 8         int count = 1;
 9         for(int i = 1; i < array.length; i++){
10             if(array[i] == soldier){
11                 count++;
12             }else{
13                 count--;
14                 if(count == 0){
15                     soldier = array[i];
16                     count++;
17                 }
18             }
19         }
20         count = 0;
21         for(int i = 0; i < array.length; i++){
22             if(array[i] == soldier){
23                 count++;
24             }
25         }
26         return (count > array.length / 2) ? soldier : 0;
27     }
28 }

 

Guess you like

Origin www.cnblogs.com/hi3254014978/p/12588435.html