-
Notifications
You must be signed in to change notification settings - Fork 0
/
arr06.java
52 lines (38 loc) · 978 Bytes
/
arr06.java
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
52
//Given an array of size N-1 such that it only contains distinct
//integers in the range of 1 to N. Find the missing element.
//Input:
//N = 5
//A[] = {1,2,3,5}
//Output: 4
package Array;
import java.util.Arrays;
public class arr06 {
// PPROACHJ - 1
public static int MissingNumber(int array[], int n) {
// Your Code Here
int missing =n;
Arrays.sort(array);
for(int i =0; i < array.length;i++){
if(array[i] != (i+1)){
missing = i+1;
break;
}
}
return missing;
}
// APPROACH -2
public static int MissingNumber2(int array[], int n) {
int actualSum = n*(n+1)/2;
int sum = 0;
for(int i=0; i<n-1; i++) {
sum+=array[i];
}
return actualSum - sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int A[] = {1,3,4,5,6};
int ans = MissingNumber(A , 5);
System.out.println(ans);
}
}