等差数列中缺失的数字
难度:
标签:
题目描述
代码结果
运行时间: 22 ms, 内存: 16.1 MB
/*
* Problem: Missing Number In Arithmetic Progression (Leetcode 1228)
* Given an array that represents elements of an arithmetic progression in order,
* one element is missing in the progression. Find the missing element.
*
* Approach using Java Streams:
* 1. Calculate the expected difference (common difference) of the progression.
* 2. Use IntStream to iterate through the array indices and find where the difference
* between consecutive elements is not equal to the expected difference.
* 3. If a mismatch is found, return the missing number by adding the expected difference
* to the previous element.
*/
import java.util.stream.IntStream;
public class MissingNumberInAPStream {
public int missingNumber(int[] arr) {
int n = arr.length;
int totalDifference = arr[n-1] - arr[0];
int commonDifference = totalDifference / n;
return IntStream.range(0, n - 1)
.filter(i -> arr[i + 1] - arr[i] != commonDifference)
.mapToObj(i -> arr[i] + commonDifference)
.findFirst()
.orElse(-1);
}
}
解释
方法:
这个题解利用了等差数列的性质。首先,计算原始等差数列(假设没有数字缺失的情况下)的长度,这是给定数组长度加一。接着,使用等差数列的首项和末项计算原始数组的理论总和。然后,计算实际给定数组的总和。原始的数组总和减去当前的数组总和,得到的差值就是被删除的那个数字。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在题解中,如何确保使用首项和末项计算的等差数列总和是正确的?是否考虑了缺失数字可能在首位或末位的情况?
▷🦆
题解假设数组是按等差数列顺序排列的,如果输入数组的顺序被打乱,这种方法还适用吗?
▷🦆
计算原始等差数列的总和时直接使用了数组的首尾元素,这种方法是否依赖于数组至少有两个元素?如果数组只有一个元素或为空,该如何处理?
▷🦆
题解中提到的原始数组总和减去当前数组总和得到缺失的数字,这种方法是否有可能在某些特殊情况下出现计算错误?
▷