[LeetCode] 645. Set Mismatch

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Example 2:

Input: nums = [1,1]
Output: [1,2]

Constraints:

  • 2 <= nums.length <= 104
  • 1 <= nums[i] <= 104

错误的集合。

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

给定一个数组 nums 代表了集合 S 发生错误后的结果。

请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/set-mismatch
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题做法很多,我给出一个O(n)的思路。我们需要遍历两次input数组,第一次遍历的时候,因为数字的范围是在1 - N之间,所以我们可以将遇到的数字 - 1,变为下标,然后把对应下标上的数字改成负数,如果在修改过程中发现对应下标上的数字已经被改成负数了,那么说明那个下标是重复出现的。

第二遍扫描我们如果发现有数字是大于0的,则说明以他作为下标是缺失的,那么那个缺失的数字就是 nums[i] + 1。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int[] findErrorNums(int[] nums) {
 3         int dup = -1;
 4         int missing = -1;
 5         for (int n : nums) {
 6             if (nums[Math.abs(n) - 1] < 0) {
 7                 dup = Math.abs(n);
 8             } else {
 9                 nums[Math.abs(n) - 1] *= -1;
10             }
11         }
12 
13         for (int i = 0; i < nums.length; i++) {
14             if (nums[i] > 0) {
15                 missing = i + 1;
16             }
17         }
18         return new int[] { dup, missing };
19     }
20 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14472342.html