【LeetCode】645. Set Mismatch 解题报告(Python)

本文介绍了一种解决LeetCode上特定问题的方法,该问题要求从一个包含重复和缺失数字的数组中找出这两个数字。提供了两种解决方案,一种是通过哈希表统计数字出现的次数来定位错误数字,另一种是通过数学计算快速得出答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/



题目地址: https://leetcode.com/problems/set-mismatch/description/

题目描述

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.

题目大意

数组正常的状态是1~N,但是有个数字重复出现了,导致覆盖了另外一个数字,现在要求重复出现的数字,和缺失的数字。

解题方法

Hash方法

这个题明显使用hash的思想。把每个位置出现的次数统计一下,找出出现了2次和0次的数字的位置即可。

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        hashs = [0] * len(nums)
        missing = -1
        for i in range(len(nums)):
            hashs[nums[i] - 1] += 1
        return [hashs.index(2) + 1, hashs.index(0) + 1]

直接计算

268. Missing Number很像,直接计算出来也可以,速度稍快点。

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        N = len(nums)
        nset = set(nums)
        missing = N * (N + 1) / 2 - sum(nset)
        duplicated = sum(nums) - sum(nset)
        return [duplicated, missing]

日期

2018 年 2 月 3 日
2018 年 11 月 21 日 —— 又是一个美好的开始

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值