leetcode 645. Set Mismatch

来源:互联网 发布:主升浪起爆点公式源码 编辑:程序博客网 时间:2024/06/02 03:35

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.

本题题意很简单就是寻找一个缺失元素和一个重复元素,最直接的方法就是直接统计即可,但是发现了一个有意思的方法:它是通过做交换把存在的值交换到对应的位置,然后做一次统计

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public:    vector<int> findErrorNums(vector<int>& nums)    {        for (int i = 0; i<nums.size(); i++)         {            while (nums[i] != nums[nums[i] - 1])                swap(nums[i], nums[nums[i] - 1]);        }        for (int i = 0; i<nums.size(); i++)        {            if (nums[i] != i + 1)                return{ nums[i], i + 1 };        }    }    vector<int> findErrorNumsByLoop(vector<int>& nums)    {        vector<int> res(2, 0), cnt(nums.size(), 0);        for (int num : nums)             ++cnt[num - 1];        for (int i = 0; i < cnt.size(); ++i)         {            if (cnt[i] == 2)                 res[0] = i + 1;            else if (cnt[i] == 0)                res[1] = i + 1;        }        return res;    }};
原创粉丝点击