构造一个1-N的排列,满足不存在
For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
一个很有趣的构造题目, https://www.dreamwings.cn/leetcode932/5327.html 这里讲的很清楚了
public int[] beautifulArray(int N) {
List<Integer> res = new ArrayList<>();
res.add(1);
while (res.size() < N) {
List<Integer> l1 = res.stream().map(e -> e * 2 - 1).collect(Collectors.toList());
List<Integer> l2 = res.stream().map(e -> e * 2).collect(Collectors.toList());
List<Integer> l = new ArrayList<>();
l.addAll(l1);
l.addAll(l2);
res = l;
}
return res.stream().filter(e -> e <= N).mapToInt(Integer::intValue).toArray();
}

本文深入探讨了一种构造1-N排列的算法,确保任意i<j,不存在k使得A[k]*2=A[i]+A[j]。通过迭代过程,利用流操作和集合合并,实现了高效生成满足条件的整数数组。
326

被折叠的 条评论
为什么被折叠?



