既然题目要求结果中有且仅有 \(k\)
个整数,那么我们可以取 \(1, 2, ..., k\)
这 \(k\) 个数构造,将数组每 \(k + 1\)
个划分为一组,组内很容易构造出相邻数组差为 \(1, 2, ..., k\) 的整数如 \([i, i + k, i + 1, i + k - 1, ...]\),
而组间最大差值肯定不会超过 \(k\).
PS: 其实简单一点的话构造一组就够了,后面的递增排列即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Code language: Python classSolution: defconstructArray(self, n: int, k: int) -> List[int]: # k 个不同的整数我们取 1, 2, ..., k ans = [0] * n p = 0 for i inrange(1, n + 1, k + 1): left, right = i, min(n, i + k) while left <= right: ans[p] = left left += 1 p += 1 if left > right: break ans[p] = right right -= 1 p += 1 # assert k == (s := len(Counter(abs(ans[i] - ans[i - 1]) for i in range(1, n)))), f"{k=}, {s=}" # 简单校验下结果正不正确 return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Code language: Java classSolution { publicint[] constructArray(int n, int k) { // k 个不同的整数我们取 1, 2, ..., k int[] ans = newint[n]; for (inti=1, p = 0; i <= n; i += k + 1) { for (intleft= i, right = Math.min(n, i + k); left <= right; ) { ans[p++] = left; if (++left > right) break; ans[p++] = right--; } } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: vector<int> constructArray(int n, int k){ // k 个不同的整数我们取 1, 2, ..., k vector<int> ans(n); for (int i = 1, p = 0; i <= n; i += k + 1) { for (int left = i, right = min(n, i + k); left <= right; ) { ans[p++] = left; if (++left > right) break; ans[p++] = right--; } } return ans; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Code language: JavaScript */ /** * @param {number} n * @param {number} k * @return {number[]} */ var constructArray = function(n, k) { // k 个不同的整数我们取 1, 2, ..., k const ans = newArray(n).fill(0); for (let i = 1, p = 0; i <= n; i += k + 1) { for (let left = i, right = Math.min(n, i + k); left <= right; ) { ans[p++] = left; if (++left > right) break; ans[p++] = right--; } } return ans; };