645. Set Mismatch挑出不匹配的元素和应该真正存在的元素

本文介绍了一种高效算法,用于在一个包含从1到n的整数集合中找到重复及缺失的数字,通过直接操作数组元素避免了额外的空间开销。

[抄题]:

he set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

 [暴力解法]:

hashset

时间分析:

空间分析:n

 [优化后]:

时间分析:

空间分析:1

[奇葩输出条件]:

[奇葩corner case]:

  1. 把数字1对应到nums[0],为了不出现溢出,需要-1

[思维问题]:

[一句话思路]:

为了优化空间,判断重复性时 直接*(-1

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

[画图]:

[一刷]:

  1. 循环中先写退出条件,再写正常条件

[二刷]:

  1. 标记元素为负数之后,记得需要变回正数才能正常返回

[三刷]:

[四刷]:

[五刷]:

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

[总结]:

为了优化空间,判断重复性时 直接*(-1)

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

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

[关键模板化代码]:

//for loop, * (-1), res[0]
        for (int num : nums) {
            if (nums[Math.abs(num) - 1] < 0) {
                res[0] = Math.abs(num);
            }else {
                nums[Math.abs(num) - 1] *= (-1);
            }
        }

[其他解法]:

[Follow Up]:

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

287. Find the Duplicate Number 快慢指针可以找重复?不是找中点么

 [代码风格] :

class Solution {
    public int[] findErrorNums(int[] nums) {
        //ini
        int[] res = new int[2];
        
        //cc
        if (nums == null || nums.length == 0) {
            return res;
        }
        
        //for loop, * (-1), res[0]
        for (int num : nums) {
            if (nums[Math.abs(num) - 1] < 0) {
                res[0] = Math.abs(num);
            }else {
                nums[Math.abs(num) - 1] *= (-1);
            }
        }
        
        //find res[1]
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                res[1] = i + 1;
            }
        }
        
        //return 
        return res;
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/8947574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值