R3-图篇

饭前一道题
思路:
单向构造

class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        m=n=len(adjacentPairs)
        #n表示数组元素总数
        n+=1
        #统计
        dict=defaultdict(int)
        #存储关系哈希表
        hashmap=defaultdict(list)
        for a,b in adjacentPairs:
            dict[a]+=1
            dict[b]+=1
            hashmap[a].append(b)
            hashmap[b].append(a)
        #数组开始的元素
        start=-1
        for i,v in dict.items():
            if v==1:
                start = i
                break
        ret=[0]*n
        ret[0]=start
        ret[1]=hashmap[start][0]
        for i in range(2,n):
            x=ret[i-1]
            for j in hashmap[x]:
               if j!=ret[i-2]:
                 ret[i]=j
        return ret

ps:也能用双向构造(双指针法)---任取一个元素放在nums,然后两边遍历







![[NISACTF 2022]ezstack-入土为安的第十四天](https://i-blog.csdnimg.cn/direct/7961db3ed1d348ffab6b77659db003a4.png)








![[CR]厚云填补_MSDA-CR](https://i-blog.csdnimg.cn/direct/11d8e4cf4b424dc28d79f22faf238cdd.png)


