首页 > 编程语言 > 详细

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

时间:2020-02-21 21:12:13      阅读:69      评论:0      收藏:0      [点我收藏+]

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!