码迷,mamicode.com
首页 > 编程语言 > 详细

找数组中重复次数超过数组长度一半的元素

时间:2017-10-14 15:04:29      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:class   元素   alt   main   print   time   eth   amp   out   

找数组中重复次数超过数组长度一半的元素

进行标号的遍历数组,因为某个元素超过一半,保存数组中的数字和其出现次数 

如果下一个相同则次数加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 }

 

找数组中重复次数超过数组长度一半的元素

标签:class   元素   alt   main   print   time   eth   amp   out   

原文地址:http://www.cnblogs.com/zfc-java/p/7666827.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!