-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSmallest Positive Integer.java
More file actions
67 lines (50 loc) · 1.3 KB
/
Smallest Positive Integer.java
File metadata and controls
67 lines (50 loc) · 1.3 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Given an unsorted array of integers,
return the smallest positive integer
eg:
arr = [1,2,0] => ans = 3
arr = [3,4,-1,1] => ans = 2
arr = [7,8,9,11,12] => ans = 1
*/
//Solution:
package com.rishabh;
public class FindMissingPositiveNumber {
public static void main(String[] args) {
System.out.println(findMissingPositiveNumbe(new int[] {3,4,-1,1}));
}
private static int findMissingPositiveNumbe(int[] arr){
int n = arr.length;
int contains = 0;
for (int i = 0; i < n; i++) {
if(arr[i] == 1) {
contains++;
break;
}
}
if(contains == 0){
return 1;
}
for (int i = 0; i < n;i++){
if(arr[i] <= 0 || arr[i] > n){
arr[i] = 1;
}
}
for (int i = 0; i < n; i++) {
int a = Math.abs(arr[i]);
if (a == n) {
arr[0] = -Math.abs(arr[0]);
} else {
arr[a] = -Math.abs(arr[a]);
}
}
for (int i = 1; i < n; i++) {
if (arr[i] > 0) {
return i;
}
}
if(arr[0] > 0) {
return n;
}
return n + 1;
}
}