forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMissingAndRepeatingElements.java
46 lines (42 loc) · 1.52 KB
/
MissingAndRepeatingElements.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
package com.rampatra.arrays;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 9/7/15
* @time: 10:54 AM
*/
public class MissingAndRepeatingElements {
/**
* Finds two numbers in an unsorted array of size n with elements in range from
* 1 to n where one number from set {1, 2, …n} is missing and one number occurs
* twice in array.
*
* @param a
* @return an array where 1st element is the repeating element and 2nd is the missing one
*/
public static int[] findMissingAndRepeatingElements(int[] a) {
int[] result = new int[2];
for (int i = 0; i < a.length; i++) {
// we use indices to mark already encountered numbers
if (a[Math.abs(a[i]) - 1] < 0) {
result[0] = Math.abs(a[i]); // repeating element
} else {
a[Math.abs(a[i]) - 1] = -a[Math.abs(a[i]) - 1];
}
}
// no. is +ve means its index wasn't encountered
for (int i = 0; i < a.length; i++) {
if (a[i] > 0) {
result[1] = i + 1; // missing element
}
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{3, 1, 3})));
System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 3, 6, 2, 1, 1})));
System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 4, 6, 2, 5, 1})));
}
}