数组中最长的方波
难度:
标签:
题目描述
You are given an integer array nums
. A subsequence of nums
is called a square streak if:
- The length of the subsequence is at least
2
, and - after sorting the subsequence, each element (except the first element) is the square of the previous number.
Return the length of the longest square streak in nums
, or return -1
if there is no square streak.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,3,6,16,8,2] Output: 3 Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16]. - 4 = 2 * 2. - 16 = 4 * 4. Therefore, [4,16,2] is a square streak. It can be shown that every subsequence of length 4 is not a square streak.
Example 2:
Input: nums = [2,3,5,6,7] Output: -1 Explanation: There is no square streak in nums so return -1.
Constraints:
2 <= nums.length <= 105
2 <= nums[i] <= 105
代码结果
运行时间: 97 ms, 内存: 32.3 MB
/*
题目思路:
1. 使用Java Stream处理输入数组。
2. 寻找所有可能的子序列组合。
3. 验证每个子序列是否是方波。
4. 找出最长的方波长度。
*/
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Solution {
public int longestSquareWave(int[] nums) {
List<Integer> sortedNums = IntStream.of(nums).sorted().boxed().collect(Collectors.toList());
int maxLength = -1;
for (int i = 0; i < sortedNums.size(); i++) {
for (int j = i + 1; j < sortedNums.size(); j++) {
int length = 1;
int current = sortedNums.get(j);
while (Math.sqrt(current) % 1 == 0 && sortedNums.contains((int)Math.sqrt(current))) {
length++;
current = (int) Math.sqrt(current);
}
if (length > 1) {
maxLength = Math.max(maxLength, length);
}
}
}
return maxLength == 1 ? -1 : maxLength;
}
}
解释
方法:
本题解的思路是首先将数组转换为集合,以去除重复元素。然后遍历集合中的每个元素,对于每个元素 x,检查 x 的平方是否在集合中。如果在,就继续检查 x 的平方的平方,以此类推,直到找不到为止。这样可以找到以 x 开头的最长方波的长度。最后返回所有方波中的最大长度。
时间复杂度:
O(n log n)
空间复杂度:
O(n)
代码细节讲解
🦆
题解中提到将数组转换为集合以去除重复元素,这一步是否对最终结果有可能产生影响,例如如果原数组中重复的元素可以构成更长的方波呢?
▷🦆
在计算每个元素的平方时,题解中没有明确是否考虑了数字溢出的问题,这在实际实现时应如何处理?
▷🦆
题解中使用了x *= x来计算平方,这种方法是否会导致忽略掉一些有效的方波序列,比如一个元素和它的平方不连续但仍在集合中的情况?
▷🦆
题解中提到的算法中,最长方波长度初始化为-1,但在实际代码实现中,是否需要有一个初始判断来确保至少存在一个合法的方波?
▷