LeetCode 448. Find All Numbers Disappeared in an Array

问题:

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

 



分析:

1 要不要排序? 如果要排序, 则线性运行时间的排序算法一定会消耗额外的存储空间。

所以存在不需要排序的算法。

 

2 曾尝试找相同元素,但该方法也不可行。

 

 

1 计数排序。

复制代码
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
        int[] counts = new int[nums.length];
        
        for(int i=0; i<nums.length; i++) {
            counts[nums[i]-1]++;
        }
        
        List<Integer> returnList = new ArrayList<Integer>();
        for(int i=0; i<nums.length; i++) {
            if(counts[i]==0) {
                returnList.add(i+1);
            }
        }
        
        return returnList;
    }
}
复制代码

 

result:

分析:

虽然知道可以不用排序,但找不到这种方法是什么。。

看了discuss区的讨论,知道了可以使用负数来表示看见过的数(nums[i]<0表示看到过i)。 真的是很巧妙的方法。

 

second try:

复制代码
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
         
        for(int i=0; i<nums.length; i++) {
            int val = Math.abs(nums[i]);
            if(0<nums[val-1]) {
                nums[val-1] = - nums[val-1];
            }
        }
        
        List<Integer> returnList = new ArrayList<Integer>();
        for(int i=0; i<nums.length; i++) {
            if(0<nums[i]) {
                returnList.add(i+1);
            }
        }
        
        return returnList;
    }
}
复制代码

result:

 

 

 

conclustion:

LeetCode中问你是否能找到一个空间复杂度。。的算法,一般是不做强制要求的。我觉得如果想检测提交算法的空间复杂度,还是能做到的。只是没有去做。

posted @   Zhao_Gang  阅读(83)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
历史上的今天:
2016-04-20 彤彤两周岁生日打油诗一首
点击右上角即可分享
微信分享提示