Leetcode 645. Set Mismatch 找缺值 解题报告

这道题有点简单,就是本来应该是个1到n的等差递增数列,然而给的这个数列,有一个值重复了,也就是多了一个值,少了一个值。任务就是找出多了哪个值,少了哪个值

The 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]
Note:
The given array size will in the range [2, 10000].
The given array's numbers won't have any order.

最naive的方法也能O(n)时间解决,不过另一块则是空间,一般如果你开个数组统计的话,就是空间复杂度也是O(n)。不过那个太简单了,这个就不讲了。

更为取巧的方法,就是利用题目的特性,因为给的都是正数。。所以我们可以利用数字的正负做一个判断,判断有没有重复出现,以及有没有出现。

要是只出现一次,那么对应位置的索引应该是负值,而如果多次出现,则在更新时就会提前遇到发现值是负值。。此题是python解的

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        duplicate = -1
        dismatch = -1
        for i in range(n):
            if nums[abs(nums[i]) - 1] < 0:
                duplicate = abs(nums[i]) 
            else:
                nums[abs(nums[i]) - 1] *= -1
        for i in range(n):
            if nums[i] > 0:
                dismatch = i + 1
        return [duplicate, dismatch]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值