I am trying to answer the following question: given a sorted array with some sequenced numbers and some non-sequenced numbers, write an algorithm that obtains a pair {start, end} for each group of consecutive numbers. Consecutive numbers have difference of 1 only.
So far, I can think of the brute force method only:
public static void main(String[] args) {
int[] array = { 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 20, 22, 23, 24, 27 };
Map<Integer, Integer> list = new HashMap<Integer, Integer>();
list = findIndex(array);
}
// Bruteforce
private static Map<Integer, Integer> findIndex(int[] array) {
Map<Integer, Integer> list = new HashMap<Integer, Integer>();
int x = -1, y = -1;
int end = array.length;
for (int i = 0; i < end; i++) {
x = i;
while (i < end - 1) {
if (array[i] + 1 == array[i + 1]) {
i++;
y = i;
} else {
if (x != y && x >= 0) {
list.put(x, y);
System.out.println("i = " + x + " to j = " + y);
i = i + 1;
break;
}
}
}
}
return list;
}
Output :
i = 0 to j = 5
i = 7 to j = 10
i = 12 to j = 14
It works fine, but how do I improve time complexity?
You don't need to nest loops for this:
int end = array.length;
if (end > 0) {
int start = 0;
for (int i = 1; i < end; i++) {
if (array[i] != array[i - 1] + 1) {
if (i - start > 1) {
list.put(start, i - 1);
System.out.println("i = " + start + " to j = " + (i - 1));
}
start = i;
}
}
if (end - start > 1) {
list.put(start, end - 1);
System.out.println("i = " + start + " to j = " + (end - 1));
}
}