Java 预备题

JAVA技巧(找出一个数组中出现次数最多的那个元素)

【网络综合 - 计算机等级考试(NCRE)】
 这个问题问的人比较多比较高,Examda提示:是写一个程序判断一个数组中出现次数最多的那个元素。
  给出的代码是:
  import java.util.*;
  public class FindMostEle {
  private static HashMap map;
  public static HashMap mostEle(String[] strArray){
  map = new HashMap();
  String str = "";
  int count = 0;
  int result = 0;
  for(int i=0; i  str += strArray[i];
  for(int i=0; i  String temp = str.replaceAll(strArray[i], "");
  count = (str.length() - temp.length())/strArray[i].length();
  if (count > result){
  map.clear();
  map.put(strArray[i], count);
  result = count;
  }
  else if(count == result)
  map.put(strArray[i], count);
  }
  return map;
  }
  public static void main(String args[]){
  String[] strArray = {"11", "11", "2", "2", "4", "5", "4"};
  HashMap result = mostEle(strArray);
  ArrayList c = new ArrayList(result.values());
  Set s = result.keySet();
  System.out.print("一共有"+ result.size() +"元素最多。它们分别是");
  System.out.print(s);
  System.out.println(",分别出现了"+ c.get(0) +"次。");
  }
  }
  结果是:
  一共有3元素最多。它们分别是[2, 11, 4],分别出现了2次。

一个数组中的部分数存入另一个数组中

返回两个数组交叉数组。

猜你喜欢

转载自oywl2008.iteye.com/blog/1583477