LeetCode Solutions
645. Set Mismatch
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
int duplicate;
for (const int num : nums)
if (nums[abs(num) - 1] < 0)
duplicate = abs(num);
else
nums[abs(num) - 1] *= -1;
for (int i = 0; i < nums.size(); ++i)
if (nums[i] > 0)
return {duplicate, i + 1};
throw;
}
};
class Solution {
public int[] findErrorNums(int[] nums) {
int duplicate = 0;
for (final int num : nums) {
if (nums[Math.abs(num) - 1] < 0)
duplicate = Math.abs(num);
else
nums[Math.abs(num) - 1] *= -1;
}
for (int i = 0; i < nums.length; ++i)
if (nums[i] > 0)
return new int[] {duplicate, i + 1};
throw new IllegalArgumentException();
}
}
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
for num in nums:
if nums[abs(num) - 1] < 0:
duplicate = abs(num)
else:
nums[abs(num) - 1] *= -1
for i, num in enumerate(nums):
if num > 0:
return [duplicate, i + 1]