一道java面试题

题目:
一个数组,“支配者”是在数组中出现频率超过一半的整数,
例如[3,4,3,2,-1,3,3,3]数值“3”出现过5次,5除以8大于0.5
所以数值“3”是一个支配者;
而在这个数组中的支配者出现在数组下标[0,2,4,6,7]
写一个函数,在给定的整数数组中找出支配者所在的任意一个数组下标,如果一个数组中没有支配者返回-1;

 

解决代码如下:

Java代码 复制代码
  1. public class ArrayOperate {   
  2.     static List<Integer> find(int[] a) {   
  3.         int length = a.length;   
  4.         int half = length / 2;   
  5.         int count = 0;   
  6.         List<Integer> list = new ArrayList<Integer>();   
  7.         for (int i = 0; i < length; i++) {   
  8.             for (int j = 0; j < length; j++) {   
  9.                 if (a[i] == a[j]) {   
  10.                     list.add(j);   
  11.                     count++;   
  12.                 }   
  13.             }   
  14.             if (count > half) {   
  15.                 break;   
  16.             } else {   
  17.                 count = 0;   
  18.                 list.clear();   
  19.             }   
  20.         }   
  21.         if (list.size() == 0) {   
  22.             list.add(-1);   
  23.         }   
  24.         return list;   
  25.     }   
  26.   
  27.     public static void main(String[] args) {   
  28.         int[] a = {1,2,3,2,2,6,2,8,2,2};   
  29.         int [] b = {2,1,2,1,1,3,1,1,2,2,2,1};   
  30.         List<Integer> result = find(b);   
  31.         for (int i : result) {   
  32.             System.out.print(i + " ");   
  33.         }   
  34.     }   
  35. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值