1. 程式人生 > >找數組中重復次數超過數組長度一半的元素

找數組中重復次數超過數組長度一半的元素

數字 false time log system -s 次數 stat ==

找數組中重復次數超過數組長度一半的元素

進行標號的遍歷數組,因為某個元素超過一半,保存數組中的數字和其出現次數

如果下一個相同則次數加1,不同減1,如果次數變為0則保存數字為下一個數,最終情況是出現次數最多的元素

最終保存下來,然後檢查是否超過半數。

 1 package cn.com.zfc.example;
 2 
 3 /**
 4  * 找數組中重復次數超過數組長度一半的元素
 5  * 
 6  * @author zfc
 7  *
 8  */
 9 public class MoreHalfArray {
10     public static void main(String[] args) {
11 int[] array = { 3,1,2,3,2 }; 12 moreThanHalf(array); 13 } 14 15 public static void moreThanHalf(int[] array) { 16 int result = array[0]; 17 int time = 0; 18 for (int i = 0; i < array.length; i++) { 19 if (time == 0) { 20 result = array[i];
21 time = 1; 22 } else if (array[i] == result) { 23 time++; 24 } else { 25 time--; 26 } 27 } 28 System.out.println(result); 29 30 if (confirmNum(array, result)) { 31 System.out.println("exsit this element is:" + result);
32 } else { 33 System.out.println("not found this element!"); 34 } 35 } 36 37 // 判斷此元素的重復次數是否大於數組長度的一半 38 public static boolean confirmNum(int[] array, int number) { 39 int time = 0; 40 for (int i = 0; i < array.length; i++) { 41 if (array[i] == number) { 42 time++; 43 } 44 } 45 if (time * 2 > array.length) { 46 return true; 47 } else { 48 return false; 49 } 50 } 51 }

找數組中重復次數超過數組長度一半的元素