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.
這道題給了我們一個長度為n的數組,說里面的數字是從1到n,但是有一個數字重復出現了一次,從而造成了另一個數字的缺失,讓我們找出重復的數字和缺失的數字。那么最直接的一種解法就是統計每個數字出現的次數了,然后再遍歷次數數組,如果某個數字出現了兩次就是重復數,如果出現了0次,就是缺失數,參見代碼如下:
解法一:
class Solution { public: vector<int> findErrorNums(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 (res[0] != 0 && res[1] != 0) return res; if (cnt[i] == 2) res[0] = i + 1; else if (cnt[i] == 0) res[1] = i + 1; } return res; } };
我們來看一種更省空間的解法,這種解法思路相當巧妙,遍歷每個數字,然后將其應該出現的位置上的數字變為其相反數,這樣如果我們再變為其相反數之前已經成負數了,說明該數字是重復數,將其將入結果res中,然后再遍歷原數組,如果某個位置上的數字為正數,說明該位置對應的數字沒有出現過,加入res中即可,參見代碼如下:
解法二:
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { vector<int> res(2, -1); for (int i : nums) { if (nums[abs(i) - 1] < 0) res[0] = abs(i); else nums[abs(i) - 1] *= -1; } for (int i = 0; i < nums.size(); ++i) { if (nums[i] > 0) res[1] = i + 1; } return res; } };
下面這種方法也很贊,首先我們把亂序的數字放到其正確的位置上,用while循環來不停的放,直到該數字在正確的位置上,那么一旦數組有序了,我們只要從頭遍歷就能直接找到重復的數字,然后缺失的數字同樣也就知道了,參見代碼如下:
解法三:
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}; } } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/96808/java-o-n-time-o-1-space
https://discuss.leetcode.com/topic/97091/c-6-lines-solution-with-explanation