0
面試大公司的問題:你會如何解決?從任意整數中,找到總和爲預期總和的對,返回數組結果作爲集合
給定一個任意整數的列表,找到總和爲未知期望總和的整數對。將數組結果返回到一個集合中。
這是我不得不從開始:
class NumericalEntityProcessor {
List<Integer[]> pairsThatSumToX(List<Integer> input, Integer expectedSum) {
}
}
這些是可能的解決方案2 - 但我錯過了一些東西......
class NumericalEntityProcessor {
List<Integer[]> pairsThatSumToX(List<Integer> input, Integer expectedSum) {
int n = list.size() + 2;
int expectedSum = n * (n + 1)/2;
int expectedSquaredSum = n * (n + 1) * (2 * n + 1)/6;
int sum = 0;
int squaredSum = 0;
System.out.println("SIZE :::" + list.size());
for (Object num : list) {
sum = sum + (int)num;
squaredSum = squaredSum + ((int)num * (int)num);
}
int xplusy = expectedSum - sum;
int xsquareplusysquare = expectedSquaredSum - squaredSum;
int twoxy = xplusy * xplusy - xsquareplusysquare;
int xminusy = (int) Math.sqrt(xsquareplusysquare - twoxy);
int x = (xplusy + xminusy)/2;
int y = (xplusy - xminusy)/2;
return new Integer[] { x, y };
int sum = list.stream().map(Line::getLength).collect(Collectors.summingInt(i->i));
}
}
或者,第二attempt-
public class ArrayExample1 {
public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> list = convertIntArrayToList(number);
System.out.println("list : " + list);
}
private static List<Integer> convertIntArrayToList(int[] input) {
List<Integer> list = new ArrayList<>();
for (int i : input) {
list.add(i);
}
return list;
IntSummaryStatistics stats = list.stream()
.collect(Collectors.summarizingInt(Line::getLength));
IntSummaryStatistics stats = list.stream().flatMap(a->Arrays.stream(a))
.collect(Collectors.summarizingInt(i->i));
System.out.println(stats.getSum());
}
}
}