leetcode 645. Set Mismatch

来源:互联网 发布:域名主机购买多少钱 编辑:程序博客网 时间:2024/06/02 02:50

1.题目

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.
翻译: 给一个数组S 包含从1到n的数,由于数据错误,导致其中一个数出现两次,一个数没有出现。
找出这两个数。

Example 1:

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

2.分析

不开辟额外空间的话,可以在原数组上进行操作。

遍历一遍数组S,对与每个出现的数字i,把下标为i-1的数*(-1)

每次先判断对应下标的数是否为正数,如果为负数,说明当前的数字重复。

最后,整个数组中唯一的正数对应的下标 i+1 即为没有出现的数字。

3.代码

class Solution {public:    vector<int> findErrorNums(vector<int>& nums) {        int duplicate = 0;        int missing = 0;        for (int i = 0; i < nums.size(); i++) {            nums[abs(nums[i]) - 1] *= -1;            if (nums[abs(nums[i]) - 1] < 0)//出现两次,负负得正                duplicate = abs(nums[i]);            else                nums[abs(nums[i]) - 1] *= -1;        }        for (int i = 0; i < nums.size(); i++) {            if (nums[i] > 0) {                missing = i + 1;                break;            }        }        return vector<int>{duplicate, missing};    }};
原创粉丝点击