zoukankan      html  css  js  c++  java
  • LeetCode 442. Find All Duplicates in an Array

    442. Find All Duplicates in an Array

    Description Submission Solutions

    • Total Accepted: 16589
    • Total Submissions: 32282
    • Difficulty: Medium
    • Contributors: shen5630

    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]
    

     Subscribe to see which companies asked this question.

    【题目分析】

    给定一个整数数组,数组中的元素都满足1 =< a[i] <= n。找出数组中重复出现的元素。要求不使用额外的存储空间,算法的时间复杂度是O(n)。

    【思路分析】

    对数组中的每个元素,把它当作数组的索引,把该索引对应位置的元素取反,如果发现该位置的元素已经取反,那么这个数就是重复出现的数。

    【java代码】

     1 public class Solution {
     2     public List<Integer> findDuplicates(int[] nums) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         
     5         for(int i = 0; i < nums.length; i++) {
     6             int index = Math.abs(nums[i]) - 1;
     7             if(nums[index] < 0) {
     8                 res.add(index+1);
     9             }
    10             nums[index] = -nums[index];
    11         }
    12         
    13         return res;
    14     }
    15 }
  • 相关阅读:
    2021广东省强网杯WriteUp
    2021 数字四川创新大赛WriteUp
    2021 陇剑杯wp
    2021 羊城杯WriteUP
    如何翻安全四大顶会的文章
    2021 祥云杯 wp
    codeql初探
    sqlmap应用
    sql注入2
    sql注入
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6416666.html
Copyright © 2011-2022 走看看