找出一个数组的长度Top k的升序子数组,并按长度降序输出
输入:[2,1,4,5,8,3,7,10,2,5] k=2
输出:[1,4,5,8],[3,7,10]
字节面试题,面试时有大概的思路没有写出来,结果可想悲催了
下面时自己的实现思路,抛个砖,大神有好的解法,欢迎交流
public List<List<Integer>> getTopKArray(int[] array, int k){
if(array == null){
return null;
}
Map<Integer, Integer> indexMap = new TreeMap<>();
int length = array.length;
boolean isFirst = false;
int index = 0;
int beforeValue = array[0];
for (int i = 1; i < length; i++){
if(beforeValue < array[i]){
if (!isFirst){
index = i -1;
indexMap.put(i -1, 2);
}else {
System.out.println("index = "+ index + " value = " + array[i]);
indexMap.put(index, indexMap.get(index) + 1);
}
isFirst = true;
}else {
isFirst = false;
}
beforeValue = array[i];
}
Map<Integer, Integer> sortedMap = sortedByValue(indexMap);
Iterator<Integer> keyIter = sortedMap.keySet().iterator();
int i = 0;
List<List<Integer>> topkArray = new ArrayList<>();
while (keyIter.hasNext()){
if(i >= k){
break;
}
i++;
int key = keyIter.next();
int value = sortedMap.get(key);
List<Integer> item = new ArrayList<>();
for (int j = 0; j < value; j++){
item.add(array[key+j]);
}
topkArray.add(item);
}
return topkArray;
}
//对值排序
private Map<Integer, Integer> sortedByValue(Map<Integer, Integer> oriMap){
if(oriMap == null || oriMap.isEmpty()){
return null;
}
Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
List<Map.Entry<Integer,Integer>> entryList = new ArrayList<>(oriMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
Iterator<Map.Entry<Integer, Integer>> iter = entryList.iterator();
while (iter.hasNext()){
Map.Entry<Integer, Integer> entry = iter.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}