zoukankan      html  css  js  c++  java
  • [LeetCode] 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:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [2,3]

    给定一个数组,其中的每个元素都小于数组的大小。这些元素中有些元素重复出现2次,有些只出现1次。

    要求找出哪些出现了2次的元素值,并把这些值放入数组并返回。

    思路:使用一个hashmap来存储数组中元素的索引的关系,key存储元素值,value存储索引。

    利用hashmap中key的唯一性,如果其中有重复的元素值,就可以很容易找出来。

    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            vector<int> res;
            unordered_map<int, int> m;
            for (int i = 0; i < nums.size(); i++) {
                if (!m.count(nums[i])) {
                    m[nums[i]] = i;
                    continue;
                }
                res.push_back(nums[i]);
            }
            return res;
            
        }
    };
    // 165 ms
  • 相关阅读:
    手工测试
    测试理论
    MySQL常用语法
    Linux设置静态ip
    设计模式
    Shiro
    TreeSet和TreeMap
    UDP和反射
    Linux归纳
    Spring+SpringMVC+Mybatis整合
  • 原文地址:https://www.cnblogs.com/immjc/p/8316644.html
Copyright © 2011-2022 走看看