leetcode|一起来寻找失踪的数字

今天是 Kevin 的算法之路的第 11 天。为大家讲解 LeetCode 第 448 题,是一道简单但又值得关注的题目。

每日一笑

世界上最不可思议的事情:

在网络上被杠精骂杠精。

在游戏中被傻逼骂傻逼。

在现实中被大佬夸大佬。

题目描述

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

哈希表

虽然题目中又说能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗?但是如果我不能,好歹也要告诉面试官能解题的方案。哈希表就是这么一种,牺牲空间换取时间的常用方案。

算法:

  • 我们用一个哈希表 hash 来记录我们在数组中遇到的数字。我们也可以用集合 set 来记录,因为我们并不关心数字出现的次数。
  • 然后遍历给定数组的元素,插入到哈希表中,即使哈希表中已经存在某元素,再次插入了也会覆盖
  • 现在我们知道了数组中存在那些数字,只需从 1⋯N 范围中找到缺失的数字。
  • 从 1⋯N 检查哈希表中是否存在,若不存在则添加到存放答案的数组中。

这个思路还是比较简单就不多解释了,直接上代码。

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
        // Hash table for keeping track of the numbers in the array
        // Note that we can also use a set here since we are not 
        // really concerned with the frequency of numbers.
        HashMap<Integer, Boolean> hashTable = new HashMap<Integer, Boolean>();
        
        // Add each of the numbers to the hash table
        for (int i = 0; i < nums.length; i++) {
            hashTable.put(nums[i], true);
        }
        
        // Response array that would contain the missing numbers
        List<Integer> result = new LinkedList<Integer>();
        
        // Iterate over the numbers from 1 to N and add all those
        // that don't appear in the hash table. 
        for (int i = 1; i <= nums.length; i++) {
            if (!hashTable.containsKey(i)) {
                result.add(i);
            }
        }
        
        return result;
    }
}

原地修改

如果不使用额外的空间去解决它,我们可以在输入数组本身以某种方式标记已访问过的数字,然后再找到缺失的数字。

算法:

  • 遍历输入数组的每个元素一次。
  • 我们将把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[|nums[i] |- 1] ×−1 。
  • 然后遍历数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1。

可以通过以下图片示例来帮助理解。

代码实现

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
        // Iterate over each of the elements in the original array
        for (int i = 0; i < nums.length; i++) {
            
            // Treat the value as the new index
            int newIndex = Math.abs(nums[i]) - 1;
            
            // Check the magnitude of value at this new index
            // If the magnitude is positive, make it negative 
            // thus indicating that the number nums[i] has 
            // appeared or has been visited.
            if (nums[newIndex] > 0) {
                nums[newIndex] *= -1;
            }
        }
        
        // Response array that would contain the missing numbers
        List<Integer> result = new LinkedList<Integer>();
        
        // Iterate over the numbers from 1 to N and add all those
        // that have positive magnitude in the array
        for (int i = 1; i <= nums.length; i++) {
            
            if (nums[i - 1] > 0) {
                result.add(i);
            }
        }
        
        return result;
    }
}
func findDisappearedNumbers(nums []int) []int {
    for i := 0; i < len(nums); i++ {
        newIndex := abs(nums[i]) - 1;

        if nums[newIndex] > 0 {
            nums[newIndex] *= -1
        }
    }

    var res []int

    for i:= 1;i <= len(nums); i++ {
        if nums[i-1] > 0{
            res = append(res, i)
        }
    }

    return res
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x 
}

郑重声明:

所展示代码已通过 LeetCode 运行通过,请放心食用~

在唠唠嗑

很多人都想养成好习惯,但大多数人却是三分钟热度。为了我们能一起坚持下去,决定制定如下计划(福利)

一起学算法,打卡领红包!

参与方式:

关注我的原创微信公众号「Kevin的学堂」,一起学习,一起更优秀!

打卡规则为:

「留言」“打卡XXX天” ➕「分享」到朋友圈

奖励:

连续打卡 21 天,联系本人获取 6.6 元红包一个!

连续打卡 52 天,联系本人获取 16.6 元红包一个!

连续打卡 100 天,联系本人获取 66.6 元红包一个!

长按扫码,一起进步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值