1. 程式人生 > >Java查詢陣列重複元素,並列印重複元素、重複次數、重複元素位置

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();
}
}
}