得到数组中最有效的元素和下标

来源:互联网 发布:windows的快捷方式 编辑:程序博客网 时间:2024/05/21 16:57
先看代码
  1. import java.util.Arrays;

  2. /**
  3.  * 得到数组中最有效的元素和下标.<br>
  4.  * 最有效的只出现频率超过长度一半的数据。
  5.  * 
  6.  * @author 赵学庆 www.java2000.net
  7.  */
  8. public class MyTest {
  9.   public static void main(String[] args) {
  10.     int[] values = new int[] { 535, -5505 };
  11.     int maxValue = getMax(values);
  12.     if (maxValue > Integer.MIN_VALUE) {
  13.       System.out.println("Number=" + maxValue);
  14.       for (int i = 0; i < values.length; i++) {
  15.         if (values[i] == maxValue) {
  16.           System.out.print(i + " ");
  17.         }
  18.       }
  19.     } else {
  20.       System.out.println("没有找到");
  21.     }
  22.   }

  23.   public static int getMax(int[] values) {
  24.     int[] nums = Arrays.copyOf(values, values.length);
  25.     Arrays.sort(nums);
  26.     int number = Integer.MIN_VALUE;
  27.     int count = 0;
  28.     int numbertemp = Integer.MIN_VALUE;
  29.     int counttemp = 0;
  30.     for (int num : nums) {
  31.       if (num == numbertemp) {
  32.         // 增加当前
  33.         counttemp++;
  34.       } else {
  35.         // 判断是否比前一个大
  36.         if (counttemp > count) {
  37.           number = numbertemp;
  38.           count = counttemp;
  39.         }
  40.         // 设置当前
  41.         numbertemp = num;
  42.         counttemp = 1;
  43.       }
  44.     }
  45.     // 判断是否比前一个大
  46.     if (counttemp > count) {
  47.       number = numbertemp;
  48.       count = counttemp;
  49.     }
  50.     if (1.0 * count / nums.length > 0.5) {
  51.       return number;
  52.     }
  53.     return Integer.MIN_VALUE;
  54.   }
  55. }

运行结果
Number=5
0 2 4 6










<script type="text/javascript"><!--google_ad_client = "pub-2908059660288034";/* 728x90,首页中间 创建于 08-8-14 */google_ad_slot = "5903610560";google_ad_width = 728;google_ad_height = 90;//--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>