-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetMismatch.java
More file actions
51 lines (46 loc) · 1.48 KB
/
Copy pathSetMismatch.java
File metadata and controls
51 lines (46 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://leetcode.com/problems/set-mismatch/description/
import java.util.*;
class SetMismatch {
public int[] findErrorNums(int[] nums) {
// HashSet<Integer> hs = new HashSet<>();
// int dp = 0, miss = 0;
// for(int i = 0; i < nums.length; i++){
// if(!hs.add(nums[i])){
// dp = nums[i];
// }
// System.out.println(hs); // this approach is based on hashmap
// } // T.C : O(n)
// S.C : O(n)
// for(int i = 1; i <= nums.length; i++){
// if(!hs.contains(i)){
// miss = i;
// }
// }
// return new int [] {dp, miss};
int i = 0;
int dp = 0; //T.c : O(n)
int missedNum = 0; //S.C : O(1)
int n = nums.length;
while(i < n){
int correct = nums[i] - 1;
if(nums[i] != nums[correct]){
swap(nums, i, correct);
}else{
i++;
}
}
for(int j = 0; j < n; j++){
if(nums[j] != j + 1){
dp = nums[j];
missedNum = j+1;
break;
}
}
return new int[] {dp, missedNum};
}
static void swap(int[] nums, int first, int second){
int temp = nums[first];
nums[first] = nums[second];
nums[second] = temp;
}
}