zoukankan      html  css  js  c++  java
  • 找到数组中消失的所有数字-算法刷题总结

    找到所有数组中消失的数字:

    给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
    找到所有在 [1, n] 范围之间没有出现在数组中的数字。
    您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

    示例:

    输入:
    [4,3,2,7,8,2,3,1]
    
    输出:
    [5,6]
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
    
    @author cosefy
    
    @date 2020/6/20
    */
    public class FindDisappearedNumbers {
    public static void main(String[] args) {
        int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
        List list = test1(nums);
        System.out.println(list);
    }
    
    解法一

    思路: 由于不能利用额外空间,所以可以采用参数数组作为辅助,假如数组中存在4,那么我们可以把数组下标为(4-1)处的值
    乘以-1,用来标记数组是存在4的,并且乘以-1并不会覆盖后面原本的数值,一次遍历之后,可以根据正负值得到哪些数值存在与否!
    分析:时间复杂度为n,空间复杂度为常数级。

    public static List<Integer> test1(int[] nums) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[Math.abs(nums[i]) - 1] > 0)
                nums[Math.abs(nums[i]) - 1] *= -1;
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0)
                list.add(i + 1);
    
    ​    }
    ​    return list;
    }
    }
    
  • 相关阅读:
    kuangbin_ShortPath P (HDU 4725)
    kuangbin_ShortPath O (LightOJ 1074)
    方法的定义格式
    A Better Finder Rename 9.40 Key
    [iOS] 初探 iOS8 中的 Size Class
    iOS 后台执行
    iOS7 毛玻璃效果
    PhpStorm8 注册码
    [教程] 【终极开关机加速!!】手把手教你加速Mac的开关机速度。(经验证适用10.10!)
    iOS 取应用版本
  • 原文地址:https://www.cnblogs.com/cosefy/p/13169112.html
Copyright © 2011-2022 走看看