Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【每日一题】- 2020-03-24 - 645. 错误的集合 #325

Open
azl397985856 opened this issue Mar 24, 2020 · 3 comments
Open

【每日一题】- 2020-03-24 - 645. 错误的集合 #325

azl397985856 opened this issue Mar 24, 2020 · 3 comments

Comments

@azl397985856
Copy link
Owner

@azl397985856 azl397985856 commented Mar 24, 2020

集合 S 包含从1到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复。

给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

示例 1:

输入: nums = [1,2,2,4]
输出: [2,3]
注意:

给定数组的长度范围是 [2, 10000]。
给定的数组是无序的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/set-mismatch

@MrTrans
Copy link

@MrTrans MrTrans commented Mar 24, 2020

先排序,然后二分查找吧

@azl397985856
Copy link
Owner Author

@azl397985856 azl397985856 commented Mar 24, 2020

思路

这题没有限制空间复杂度,因此直接hashmap 存储一下没问题。 不多书,我们来看一种空间复杂度$O(1)$的解法。

我们和137. 只出现一次的数字2思路基本一样,我直接复用了代码,不懂的可以看我之前写的位运算题解

这里我们的思路是,将nums的所有索引提取出一个数组idx,那么由idx和nums组成的数组构成singleNumbers的输入,其输出是唯二不同的两个数。

但是我们不知道哪个是缺失的,哪个是重复的,因此我们需要重新进行一次遍历,判断出哪个是缺失的,哪个是重复的。

代码

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        ret = 0  # 所有数字异或的结果
        a = 0
        b = 0
        for n in nums:
            ret ^= n
        # 找到第一位不是0的
        h = 1
        while(ret & h == 0):
            h <<= 1
        for n in nums:
            # 根据该位是否为0将其分为两组
            if (h & n == 0):
                a ^= n
            else:
                b ^= n

        return [a, b]

    def findErrorNums(self, nums: List[int]) -> List[int]:
        nums = [0] + nums
        idx = []
        for i in range(len(nums)):
            idx.append(i)
        a, b = self.singleNumbers(nums + idx)
        for num in nums:
            if a == num:
                return [a, b]
        return [b, a]

复杂度分析

  • 时间复杂度:$O(N)$
  • 空间复杂度:$O(1)$

更多题解可以访问我的LeetCode题解仓库:https://github.com/azl397985856/leetcode 。 目前已经接近30K star啦。

大家也可以关注我的公众号《脑洞前端》获取更多更新鲜的LeetCode题解

大家慢慢培养一下Bit Sense吧,有些时候还是很有用的。为什么呢?那还不是因为计算机底层本来就是bit运算嘛~~~

@honysyang
Copy link

@honysyang honysyang commented Apr 14, 2020

第一点:这些数据没有重复,第二点这些数据无序,第三点这些数据是连续的。所以可以二分和快速排序相结合,找到重复的后,比较前后的即可

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.