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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    只知道一个数重复两次就是画圈-快慢指针,很多数重复2次不知道怎么做

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    转一回:自己重复变成index重复,再转回到nums[index]重复。然后注意一下范围

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    判断重复需要:转一回:自己重复变成index重复,再转回到nums[index]重复。

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            //initialization
            List<Integer> result = new ArrayList<Integer>();
            
            //for loop: get the new index, add to result if negative, change to negative
            for (int i = 0; i < nums.length; i++) {
                //get the new index
                int index = Math.abs(nums[i]) - 1;
                
                //add to result if negative
                if (nums[index] < 0) result.add(index + 1);
                
                //change to negative
                else nums[index] *= (-1);
            }
            //return
            return result;
        }
    }
    /*
                    [4, 3, 2, 7, 8, 2, 3, 1]
                i    0  1  2  3  4  5  6  7
               index 3  2  1
    nums[index]*(-1) -7 -2 -3
    */
    View Code
  • 相关阅读:
    IDE警告信息不应该被忽略
    C#委托使用:多播 ,向委托注册多个方法
    C# random生成随机数全部一样
    使用dynamic动态设置属性值与反射设置属性值性能对比
    git基本使用
    sql server多数据库查询 远程数据库查询
    C# mvc统一通道使用过滤器
    拼凑json的实例
    java常考小程序
    几个触发器的实例
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9411362.html
Copyright © 2011-2022 走看看