数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
 
 1 import java.util.Stack;
 2 public class Solution {
 3     public int MoreThanHalfNum_Solution(int [] array) {
 4         if (array.length == 0) return 0;
 5         Stack<Integer> s = new Stack<>();
 6         
 7         for (int i = 0; i < array.length; ++i) {
 8             if (s.empty() || s.peek() == array[i]) {
 9                 s.push(array[i]);
10             } else {
11                 s.pop();
12             }
13         }
14         if (!s.empty()) {
15             int temp = s.peek();
16             int sum = 0;
17             for (int i = 0; i < array.length; ++i) {
18                 if (array[i] == temp){
19                     sum++;
20                 }
21             }
22             if (sum > array.length / 2) {
23                 return temp;
24             } else {
25                 return 0;
26             }
27         } else {
28             return 0;
29         }
30     }
31 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12342942.html