具有连续数字的数组 - 算法

时间:2016-01-14 23:00:06

标签: java arrays algorithm data-structures

我试图回答以下问题:给定一个带有一些序列号和一些非序列号的排序数组,编写一个算法,为每组连续数字获得一对{start,end}。连续数字只有1的差异。

到目前为止,我只能想到蛮力方法:

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;
}

输出:

i = 0 to j = 5
i = 7 to j = 10
i = 12 to j = 14

它工作正常,但我如何提高时间复杂度?

2 个答案:

答案 0 :(得分:1)

您不需要为此嵌套循环:

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));
    }
}

答案 1 :(得分:0)

初始数组排序后,您可以像这样使用此算法的O(N)实现:

private static Map<Integer, Integer> getConsecutive(final int[] array) {
    final Map<Integer, Integer> list = new TreeMap<Integer, Integer>();
    int startIndex = 0;
    int endIndex = 0;
    for (int i = 1; i < array.length; i++) {
        if (array[i - 1] + 1 == array[i])
            endIndex = i;
        else {
            if (endIndex > startIndex)
                list.put(startIndex, endIndex);
            startIndex = endIndex = i;
        }
    }
    if (endIndex > startIndex)
        list.put(startIndex, endIndex);
    return list;
}