1743. 从相邻元素对还原数组
作者:互联网
class Solution {
public int[] restoreArray(int[][] adjacentPairs) {
//1和4在二维数组中出现1次 其它出现2次
//先统计次数,然后找到出现1次的数字1
//然后找2的相邻元素3
//然后找3的相邻元素4
//遍历一遍数组,构造一个HashMap<Integer,List<Integer>>
HashMap<Integer, List<Integer>> map = new HashMap<>();
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<adjacentPairs.length;i++){
for (int j = 0; j < 2; j++) {
int key = adjacentPairs[i][j];
int adjKey = adjacentPairs[i][1-j];
if(!map.containsKey(key)) {
List<Integer> list = new ArrayList<>();
list.add(adjKey);
System.out.println(adjKey);
map.put(key, list);
}
else {
map.get(key).add(adjKey);
}
}
}
//System.out.println(map);
int[] res = new int[map.size()];
int idx=0,e=0;
for (Integer key : map.keySet()) {
List<Integer> list = map.get(key);
if(list.size()==1){
//System.out.println(key);
res[idx++]=key;
set.add(key);
e=key;
break;
}
}
//System.out.println(map.get(1).get(0));
while (set.size()!=map.size()){
List<Integer> list = map.get(e);
System.out.println(list);
for (Integer integer : list) {
if(!set.contains(integer)){
System.out.println(integer);
res[idx++] = integer;
set.add(integer);
e = integer;
}
}
}
return res;
}
}
标签:map,数组,int,list,System,相邻,key,out,1743 来源: https://blog.csdn.net/qq_39370495/article/details/119081590