Given an integer array of size N - 1, containing all the numbers from 1 to N except one, find the missing number.
Assumptions
The given array is not null, and N >= 1
Examples
A = {2, 1, 4}, the missing number is 3
A = {1, 2, 3}, the missing number is 4
A = {}, the missing number is 1
1 //time o(n) space o(n)
2 public int missing_method1(int[] array) {
3 // Write your solution here
4 //corner case
5 if (array == null){
6 return -1 ;
7 }
8 // since we know for sure there is one number missing from array
9 int size = array.length ;
10 //1: put for 1 to size into hashset
11 Set<Integer> dic = new HashSet<>(size) ;
12 for (int i = 0 ; i <size ; i++){
13 dic.add(array[i]);
14 }
15 //2: and then loop through the array and cross check with the dic
16 for (int i = 1; i <= size +1 ; i++) {
17 if (!dic.contains(i)){
18 return i;
19 }
20 }
21 return -1 ;
22 }
23
24 // time o(n) space o(1)
25 public int missing_method2(int[] array) {
26 // Write your solution here
27 //corner case
28 if (array == null){
29 return -1 ;
30 }
31 int size = array.length ;
32 int sum = 0 ;
33 for (int i = 0 ; i <size ; i++){
34 sum += array[i] ;
35 }
36 //2: and then loop through the array and cross check with the dic
37 int total = 0 ;
38 for (int i = 1; i <= size +1 ; i++) {
39 total += i ;
40 }
41 return total - sum ;
42 }
43
44 //todo: xor bit operation method save for later