class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
int a=nums.size();
vector<int> res;
for(int i=0;i<a;i++)
{
for(int j=i+1;j<a;j++)
{
if(nums[i]==nums[j])
{ res.push_back(nums[i]);
res.push_back(nums[i]+1);
}
}
}
return res;
}
};
题目:
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的集合,之后数据出错导致一个数复制到另一个位置上,导致这个集合中有一个数出现了2次,有一个数出现了0次。
题目和 LeetCode 448 Find All Numbers Disappeared in an Array非常相似,采用的解题方法也几乎是同一种,都是利用了把数当作下标来使用,利用负数做标记的方法,实现出现一次,和出现0次的区分。
代码如下: