leetcode-268. 缺失数字

题目

给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。

示例 1:

输入: [3,0,1]
输出: 2

示例 2:

输入: [9,6,4,2,3,5,7,0,1]
输出: 8

Constraints:

n == nums.length
1 <= n <= 10^4
0 <= nums[i] <= n
All the numbers of nums are unique.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Solution

Change original list

Go through the original list, use the current value as the index, and multiply the value under the new index by -1. And then go through the list, the positive number’s index is the missing value.

One special case is, 0 * -1 = 0, so use another map to store 0.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Bit manipulation

Solved after help.

Because x ^ x = 0, so we can calculate the xor from 0 to n, and then xor all the numbers in the list. And the result will be our missing value.

To simply, we can just xor the index and value at the same time, and then xor n at the end.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Similarly, we can do a sum… Sum from 0 to n first, and then subtract every element in the nums

代码

Change original list

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        special_cases = {0: False}
        for i in range(n):
            new_index = nums[i]
            if new_index < 0:
                new_index *= -1
            if new_index < n:
                if nums[new_index] == 0:
                    special_cases[0] = True
                else:
                    nums[new_index] *= -1
        for i in range(n):
            if nums[i] > 0:
                return i
            elif nums[i] == 0 and not special_cases[0]:
                return i
        return n

Bit manipulation

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        xor = 0
        for i in range(len(nums)):
            xor ^= i ^ nums[i]
        return xor ^ len(nums)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值