对在Java中跳过数字的整数数组进行分组

时间:2014-05-08 21:41:45

标签: java arrays

说我有以下int array

[1,2,3,6,7, 8, 9,20, 22]

我希望能够根据上述array向用户显示以下内容:

Numbers 1 through 3, 6 through 9, 20, 22

我怎么能这样做?基本上检查前面的数字是否等于当前数字 - 1?猜猜我刚刚回答了我自己的问题,但欢迎任何捷径/指针。

注意:只处理整数,没有任何负数(不会是整数)。

4 个答案:

答案 0 :(得分:3)

可以找到使用Ideone的实时示例here。在O(n)时间运行。


Integer[] A = {1, 2, 3, 6, 7, 8, 9, 20, 22};
int start = 0, end;

System.out.print("Numbers ");                 
while((end = start) < A.length){
    // Increment the 'end' pointer while consecutive numbers exist.
    while(end + 1 < A.length && A[end + 1] == A[end] + 1) end++;

    // If end == start: 'A[start]'
    // Else           : 'A[start] through A[end]'
    System.out.print(A[start] + 
                     (end == start ? "":(" through " + A[end])) +  
                     (end < A.length - 1 ? ", ":""));

    // Increment start pointer to next element in A
    start = end + 1;
}

答案 1 :(得分:1)

不是最好看的代码,但有效:

public static void display(int[] input) {
    String out = "Numbers ";
    int first = input[0];
    int last = -1;
    int older = first;
    for (int i : input) {
        if (i == older + 1) {
            last = i;
            older++;
        } else if (i > older + 1) {
            out += last > first ? first + " through " + last + ", " : first + ", ";
            first = i;
            older = i;
        }
        if (i == input[input.length - 1]) {
            out += last > first ? first + " through " + last : first;
        }
    }
    System.out.println(out);
}

示例:

int[] in1 = { 1, 2, 3, 6, 7, 8, 9, 20, 22 };
int[] in2 = { 1, 2, 3, 6, 7, 8, 9, 20, 21, 22 };
display(in1);
display(in2);

输出:

Numbers 1 through 3, 6 through 9, 20, 22
Numbers 1 through 3, 6 through 9, 20 through 22

答案 2 :(得分:0)

尝试类似:

int[] numberArray = [1, 2, 3, 6, 7, 8, 9, 20, 22];
int rangeStart = -999;
int rangeEnd = -999;
for (int n : numberArray) {
    if (n > rangeEnd + 1) {
        if (rangeEnd = -999) {
            System.out.print("Numbers ");
        else if (rangeEnd > rangeStart) {
            System.out.printf("%d through %d, ", rangeStart, rangeEnd);
        } else {
            System.out.printf("%d, ", rangeEnd);
        }
        rangeStart = rangeEnd = n;
    } else {
        rangeEnd = n;
    }
}
if (rangeEnd > rangeStart) {
    System.out.printf("%d through %d, ", rangeStart, rangeEnd);
} else {
    System.out.printf("%d,", rangeEnd);
}

可能需要对逗号和换行符的使用进行一些微调。

答案 3 :(得分:0)

很抱歉我的格式很糟糕,只是你能想到的一些伪代码。

for(int i = 0; i < length; i++){
    start = int[i]
    compare int[i] to int[i+1] {
        if true, store as end, compare to next in array
        else, break out
    }

    if start != end, print start through end
    else, print start
}

**编辑:并将i增加为最后的+ 1