当前位置:   article > 正文

Leetcode442. 通过哈希表找出数组重复元素_哈希表寻找两个数组相同的元素

哈希表寻找两个数组相同的元素

Leetcode442. Find All Duplicates in an Array

题目

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?

Example:
Input: The root of a Binary Search Tree like this:
[4,3,2,7,8,2,3,1]
Output: The root of a Greater Tree like this:
[2,3]

解题分析

这道题看起来很简单,用最朴素的算法,用两层循环就可以解决,但这样时间复杂度就为O(n^2)(显得有些浪费了),而题目要求我们采用O(n)的算法,所以我们只能另辟蹊径了。

我们都知道哈希表存储的key-value的值,可以通过key快速索引到value。这里我想到了C++11中的新特性unordered_map,一种特殊的哈希表,其内部元素是无序的。
我们可以用数组中的元素的值来作为key,而将它们在数组中出现的次数作为value,这样我们通过遍历整个哈希表,找出value值大于1所对应的key值就可以了,是不是很简单呢?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50314
推荐阅读
相关标签
  

闽ICP备14008679号