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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MebiuW/article/details/76277485

这道题有点简单,就是本来应该是个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]



猜你喜欢

转载自blog.csdn.net/MebiuW/article/details/76277485
今日推荐