integers which have smallest absolute difference there can be one such pair or multiple such pair

淺唱寂寞╮ 提交于 2019-12-11 02:02:39

问题


sample input= 10 -20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854

sample output = -20 30

thanks in advance i am beginner in programing

class Main {
    public static void main(String[] args) {
       int _a_size = Integer.parseInt(args[0]);
       Assert.assert2(args.length,_a_size+1);
       int[] _a = new int[_a_size];
       for(int _a_i = 0;_a_i<_a_size;_a_i++) {
          _a[_a_i] = Integer.parseInt(args[_a_i+1]);
       } 
       Operation.minDiffrence (_a);
    }
}

回答1:


You can do

public static List<int[]> minDifference(int[] values) {
    Arrays.sort(values); // O(N log N)
    List<int[]> results = new ArrayList<>();
    long minDiff = Long.MAX_VALUE;
    for(int i = 0; i < values.length-1;i++) {
        long diff = Math.abs((long) values[i+1] - values[i]);
        if (diff < minDiff) {
            results.clear();
            minDiff = diff;
        }
        if (diff == minDiff)
            results.add(Array.copyOfRange(values, i, 2));
    }
    return results;
}

What this does is maintain all the results which are the shortest so far, and if a short result is found, it discards the old ones. You get back a list of pairs of equally separated values.

Note: the calculations are performed as long to avoid overflows.




回答2:


I know this is an old question, but here is a working Java 8 solution:

Map<Integer, List<List<Integer>>> map = list.stream().flatMap(i -> list.stream()
    .map(i2 -> (i.equals(i2) || i > i2) ? null : Arrays.asList(i, i2)))
    .filter(ints -> ints != null)
    .collect(Collectors.groupingBy(o -> Math.abs(o.get(1) - o.get(0))));

It looks a bit ugly in SO's code display, but in my IDE it fits nicely on 3 lines. It returns a map where the keys are the absolute difference and the values are a list of the corresponding pairs of numbers (because there might be more than one).

You might not need it anymore, but it's always fun playing with streams.



来源:https://stackoverflow.com/questions/28189282/integers-which-have-smallest-absolute-difference-there-can-be-one-such-pair-or-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!