leetcode每日一题2021.7.25【1743. 从相邻元素对还原数组】

一、题目描述

1.题目内容

存在一个由 n 个不同元素组成的整数数组 nums ,但你已经记不清具体内容。好在你还记得 nums 中的每一对相邻元素。
给你一个二维整数数组 adjacentPairs ,大小为 n - 1 ,其中每个 adjacentPairs[i] = [ui, vi] 表示元素 ui 和 vi 在 nums 中相邻。
题目数据保证所有由元素 nums[i] 和 nums[i+1] 组成的相邻元素对都存在于 adjacentPairs 中,存在形式可能是 [nums[i], nums[i+1]] ,也可能是 [nums[i+1], nums[i]] 。这些相邻元素对可以按任意顺序出现。
返回原始数组nums 。如果存在多种解答,返回 其中任意一个即可。

2.题目示例

示例1

输入 :adjacentPairs = [[2,1],[3,4],[3,2]]
输出:[1,2,3,4]
解释:数组的所有相邻元素对都在 adjacentPairs 中。
特别要注意的是,adjacentPairs[i] 只表示两个元素相邻,并不保证其 左-右 顺序。

示例2

输入:adjacentPairs = [[4,-2],[1,4],[-3,1]]
输出:[-2,4,1,-3]
解释:数组中可能存在负数。
另一种解答是 [-3,1,4,-2] ,也会被视作正确答案。

示例3

输入:adjacentPairs = [[100000,-100000]]
输出:[100000,-100000]

3.提示

nums.length == n
adjacentPairs.length == n - 1
adjacentPairs[i].length == 2
2 <= n <= 105
-105 <= nums[i], ui, vi <= 105
题目数据保证存在一些以 adjacentPairs 作为元素对的数组 nums

二、思路

直接遍历即可。

三、数据结构资料

双哈希表。

第一个哈希表用来记录数据出现了多少次(只有首尾数据只出现一次,其余数据出现两次)。

第二个哈希表用于存放对应的相邻数对。

四、代码

class Solution 
{
    public int[] restoreArray(int[][] adjacentPairs) 
    {
        Map<Integer, Integer> count = new HashMap<Integer, Integer>();
        Map<Integer, List<Integer>> near = new HashMap<Integer, List<Integer>>();
        int[] result = new int[adjacentPairs.length + 1];
        for(int[] pair : adjacentPairs)
        {
            count.put(pair[0], count.getOrDefault(pair[0], 0) + 1);
            count.put(pair[1], count.getOrDefault(pair[1], 0) + 1);
            List<Integer> listA = near.getOrDefault(pair[0], new ArrayList<>());
            List<Integer> listB = near.getOrDefault(pair[1], new ArrayList<>());
            listA.add(pair[1]);
            listB.add(pair[0]);
            near.put(pair[0], listA);
            near.put(pair[1], listB);
        }
        for(int key : count.keySet())
        {
            if(count.get(key) == 1)
            {
                result[0] = key;
            }
        }
        for(int i = 1; i < result.length; i++)
        {
            List<Integer> next = near.get(result[i - 1]);
            if(i > 1 && next.get(0) == result[i - 2])
            {
                result[i] = next.get(1);
            }
            else
            {
                result[i] = next.get(0);
            }
        }
        return result;
    }
}

五、复杂度分析

时间复杂度O(n)
空间复杂度O(n)

执行用时时间击败比例内存消耗内存击败比例
129ms69%83.8MB62%
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值