Java gets the most efficient element and subscript in the array

Source: Internet
Author: User

Look at the code first

import java.util.Arrays;

/**
* 得到数组中最有效的元素和下标.<br>
* 最有效的只出现频率超过长度一半的数据。
*
* @author 赵学庆 www.java2000.net
*/
public class MyTest {
 public static void main(String[] args) {
  int[] values = new int[] { 5, 3, 5, -5, 5, 0, 5 };
  int maxValue = getMax(values);
  if (maxValue > Integer.MIN_VALUE) {
   System.out.println("Number=" + maxValue);
   for (int i = 0; i < values.length; i++) {
    if (values[i] == maxValue) {
     System.out.print(i + " ");
    }
   }
  } else {
   System.out.println("没有找到");
  }
 }

 public static int getMax(int[] values) {
  int[] nums = Arrays.copyOf(values, values.length);
  Arrays.sort(nums);
  int number = Integer.MIN_VALUE;
  int count = 0;
  int numbertemp = Integer.MIN_VALUE;
  int counttemp = 0;
  for (int num : nums) {
   if (num == numbertemp) {
    // 增加当前
    counttemp++;
   } else {
    // 判断是否比前一个大
    if (counttemp > count) {
     number = numbertemp;
     count = counttemp;
    }
    // 设置当前
    numbertemp = num;
    counttemp = 1;
   }
  }
  // 判断是否比前一个大
  if (counttemp > count) {
   number = numbertemp;
   count = counttemp;
  }
  if (1.0 * count / nums.length > 0.5) {
   return number;
  }
  return Integer.MIN_VALUE;
 }
}

Run results

Number=5
0 2 4 6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.