Java查找数组重复元素,并打印重复元素、重复次数、重复元素位置

面试题查找重复元素并打印重复次数和重复位置,一顿懵逼,回来死磕写下来,打印指定重复次数和最大次数,其他在此基础上可以再更新

package sort;

import org.testng.annotations.Test;
import sun.org.mozilla.javascript.internal.ast.NewExpression;

import java.util.*;

/**
* Created by liangwei on 2018/10/18.
*/
public class SearchString {
/**
* 找出重复字符、记录重复字符次数、记录重复字符位置
* @param str
* @return map
*/
public Map get_str_count_index(String[] str){
Map<String,Map<Integer,ArrayList>> map = new HashMap<String ,Map<Integer,ArrayList>>();//key值记录重复的字符串,value记录出现的次数和位置
int i = 0;
for (String s:str ){
if (map.get(s)==null){
Map<Integer,ArrayList> count_where = new HashMap<Integer ,ArrayList>();//key值记录重复字符串出现的次数,value记录重复字符出现的位置
int count = 1;//重复字符串计数器
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);//重复字符串下标
count_where.put(count,list);
map.put(s,count_where);
i++;
}else {
for (int c:map.get(s).keySet()){
ArrayList index = map.get(s).get(c);
index.add(i);//增加出现index位置
c++;
map.get(s).put(c,index);//更新计数器和下标信息
map.get(s).remove(--c);//删除掉之前的记录信息
}
i++;
}
}
return map;
}

public void display(String[] arry) throws Exception{
if (arry==null){
throw new Exception("输入数组为空,请重新输入");
}
Map<String,HashMap<Integer,ArrayList>> map = get_str_count_index(arry);
ArrayList count = new ArrayList<Integer>();//存取所有字符串出现的次数
for (Map.Entry<String,HashMap<Integer,ArrayList>> key : map.entrySet()){//循环获取记录字符串重复次数和位置map
for (Map.Entry<Integer,ArrayList> map1 :key.getValue().entrySet()){//循环获取记录字符串重复次数
count.add(map1.getKey());
}
}
// Arrays.sort(count.toArray());
Collections.sort(count);//对集合排序,默认是升序,最后一个是重复次数最多的
//打印重复次数最多的元素信息
for (String key : map.keySet()){//循环获取所有的重复字符串
for (int c:map.get(key).keySet()){//循环获取重复字符串的次数
if (c == count.get(count.size()-1)){//和最大重复次数对比,相等就代表当前的字符串是重复次数最多的那个
System.out.printf("重复次数最多的字符串是:%s,重复次数%d,所在位置:%s\n",key,c,map.get(key).get(c));
}
}
}
//输出指定重复次数的字符串信息
for (String key :map.keySet()){
for (int c:map.get(key).keySet()){
if (c==5||c==6||c==1){
System.out.printf("重复字符串:%s,重复次数:%d,重复字符串出现位置:%s\n",key,c,map.get(key).get(c));
}
}
}
}

public static void main(String[] args) {
String[] arry = {"aa","bb","cc","bb","aa","ooo","dd","aaa","aa"};
// String[] arry = {};
SearchString searchString = new SearchString();
try {
searchString.display(arry);
} catch (Exception e) {
e.printStackTrace();
}
}
}

猜你喜欢

转载自www.cnblogs.com/lanrumeng/p/9814088.html