我是Java 8的新手,我尝试在Java 8中编写以下代码段,但确实起作用。
static int getMissingNo(int a[], int n) {
int i, total;
total = (n + 1) * (n + 2) / 2;
for (i = 0; i < n; i++)
total -= a[i];
return total;
}
// this is waht i tried in java 8
int total = (n+1) * (n+2) /2;
unicArray.stream().forEach(e->{
total = total - e;
});
代码段给我一个编译错误,说局部变量应该是最终变量,但是如果是最终变量,我该如何返回该值
答案 0 :(得分:1)
请在下面找到代码:
static List<Integer> getMissingNo(int[] a, int n) {
List<Integer> listOfDistinctElements = Arrays.stream(a)
.boxed()
.distinct().collect(Collectors.toList());
List<Integer> elemntsLeftOut = new ArrayList<>();
IntStream.range(1, listOfDistinctElements.get(listOfDistinctElements.size()-1)).forEach(index ->
{
if(!listOfDistinctElements.contains(index)){
elemntsLeftOut.add(index);
}
});
return elemntsLeftOut;
}
答案 1 :(得分:0)
您可以简单地将数组total
和sum
之间的差返回为:
int expectedSum = (n + 1) * (n + 2) / 2;
int actualSum = Arrays.stream(a).sum(); // .distinct().sum() for sum of unique numbers
return expectedSum - actualSum;