zoukankan      html  css  js  c++  java
  • leetcode 442. 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]

    根据题目要求,不能用多余的内存,考虑到a[i]<=n 所以数组nums本身就是个0~n-1 的hash表,通过标记num[index]有没有被2次访问过,来统计哪些数字出现两次。

    考虑到nums[index]被标记后,还得继续使用,所以采用负号标记最好

    注意题目没有要求结果必须按照由小到大的顺序输出

    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            vector<int>v;
            for (int i = 0; i < nums.size(); ++i) {
                int index = abs(nums[i]) - 1;
                if (nums[index] < 0) v.push_back(index + 1);
                nums[index] = -nums[index];
            }
            return v;
        }
    };
  • 相关阅读:
    可运行的Java RMI示例和踩坑总结
    JS异步与同步
    Github作为Maven仓库
    Jmeter笔记
    nodeJS生成xlsx以及设置样式
    double运算的坑
    mysql零散操作
    go包的理解
    nodeJS 服务端文件上传
    webpack+thymeleaf实现数据直出
  • 原文地址:https://www.cnblogs.com/pk28/p/7341712.html
Copyright © 2011-2022 走看看