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
  • 相关阅读:
    jQuery的选择器中的通配符[id^='code']
    chorme插件 ,在浏览器上模拟手机,pad 查看网页|前端技术开发必备插件
    http://hsax.kcpci.com:81/admin/login.aspx
    ashx页面返回json字符串|jQuery 的ajax处理请求的纠结问题
    用NPOI创建Excel、合并单元格、设置单元格样式、边框的方法
    DataTable 导入到Excel的最佳选择Npoi
    隐藏和显示服务器端控件以及Html控件
    JS只能输入数字,数字和字母等的正则表达式
    把本地表导入远程表
    [flex & bison]编译器杂谈
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9411362.html
Copyright © 2011-2022 走看看