645. Set Mismatch
Description
You have a set of integers s
, which originally contains all the numbers from 1
to n
. Unfortunately, due to some error, one of the numbers in s
got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums
representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Constraints
2 <= nums.length <= 104
1 <= nums[i] <= 104
Approach
Links
GeeksforGeeks
ProgramCreek
YouTube
Examples
Input: nums = [1, 2, 2, 4]
Output: [2, 3]
Solutions
/**
* Time complexity : O(n)
* Space complexity : O(1)
*/
class Solution {
public int[] findErrorNums(int[] nums) {
int n = nums.length;
int sum = n * (n+1)/2;
int duplicate = 1;
for(int i = 0; i < n; i++) {
int index = Math.abs(nums[i])-1;
if(nums[index] < 0) {
duplicate = index+1;
} else {
sum -= Math.abs(nums[i]);
}
nums[index] = -nums[index];
}
return new int[]{duplicate, sum};
}
}
Follow up
Last updated
Was this helpful?