How would you display an array of integers as a set of ranges? (algorithm)

后端 未结 16 2934
我在风中等你
我在风中等你 2021-02-15 18:04

Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = ar         


        
16条回答
  •  情话喂你
    2021-02-15 18:07

    My solution in Java 1.5 would be:

    public static List getRanges(int... in) {
        List result = new ArrayList();
        int last = -1;
        for (int i : in) {
            if (i != (last + 1)) {
                if (!result.isEmpty()) {
                    addRange(result, last);
                }
                result.add(String.valueOf(i));
            } 
            last = i;
        }
        addRange(result, last);
        return result;
    }
    
    private static void addRange(List result, int last) {
        int lastPosition = result.size() - 1;
        String lastResult = result.get(lastPosition);
        if (!lastResult.equals(String.valueOf(last))) {
            result.set(lastPosition, lastResult + "-" + last);
        }
    }
    
    public static void main(String[] args) {
        List ranges = getRanges(1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16);
        System.out.println(ranges);
    }
    

    which outputs:

    [1, 3-6, 8, 11-12, 14-16]
    

    Greetz, GHad

提交回复
热议问题