Skip to content

Latest commit

 

History

History
165 lines (133 loc) · 4.84 KB

File metadata and controls

165 lines (133 loc) · 4.84 KB

中文文档

Description

There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.

You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.

It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.

Return the original array nums. If there are multiple solutions, return any of them.

 

Example 1:

Input: adjacentPairs = [[2,1],[3,4],[3,2]]
Output: [1,2,3,4]
Explanation: This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs[i] may not be in left-to-right order.

Example 2:

Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
Output: [-2,4,1,-3]
Explanation: There can be negative numbers.
Another solution is [-3,1,4,-2], which would also be accepted.

Example 3:

Input: adjacentPairs = [[100000,-100000]]
Output: [100000,-100000]

 

Constraints:

  • nums.length == n
  • adjacentPairs.length == n - 1
  • adjacentPairs[i].length == 2
  • 2 <= n <= 105
  • -105 <= nums[i], ui, vi <= 105
  • There exists some nums that has adjacentPairs as its pairs.

Solutions

Traverse the graph from the point where the degree is one.

Python3

class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        graph = defaultdict(list)
        for pair in adjacentPairs:
            graph[pair[0]].append(pair[1])
            graph[pair[1]].append(pair[0])
        ans = []
        vis = set()

        def dfs(idx):
            if idx in vis:
                return
            vis.add(idx)
            ans.append(idx)
            for nxt in graph[idx]:
                dfs(nxt)

        start = -1
        for idx, adj in graph.items():
            if len(adj) == 1:
                start = idx
                break

        dfs(start)
        return ans

Java

class Solution {
    public int[] restoreArray(int[][] adjacentPairs) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int[] pair : adjacentPairs) {
            graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
            graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);
        }
        List<Integer> ans = new ArrayList<>();
        Set<Integer> vis = new HashSet<>();
        int start = -1;
        for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {
            if (entry.getValue().size() == 1) {
                start = entry.getKey();
                break;
            }
        }
        dfs(graph, ans, vis, start);
        return ans.stream().mapToInt(Integer::valueOf).toArray();
    }

    private void dfs(Map<Integer, List<Integer>> graph, List<Integer> ans, Set<Integer> vis, int idx) {
        if (vis.contains(idx)) {
            return;
        }
        vis.add(idx);
        ans.add(idx);
        for (Integer next : graph.get(idx)) {
            dfs(graph, ans, vis, next);
        }
    }
}

Go

func restoreArray(adjacentPairs [][]int) []int {
	graph := make(map[int][]int)
	for _, pair := range adjacentPairs {
		graph[pair[0]] = append(graph[pair[0]], pair[1])
		graph[pair[1]] = append(graph[pair[1]], pair[0])
	}
	ans := make([]int, 0)
	vis := make(map[int]bool)
	var start int
	for idx, adj := range graph {
		if len(adj) == 1 {
			start = idx
			break
		}
	}
	dfs(graph, &ans, vis, start)
	return ans
}

func dfs(graph map[int][]int, ans *[]int, vis map[int]bool, idx int) {
	if vis[idx] {
		return
	}
	vis[idx] = true
	*ans = append(*ans, idx)
	for _, next := range graph[idx] {
		dfs(graph, ans, vis, next)
	}
}

...