对于其它的一般情况,我们可以将这两种特殊情况进行合并,即列表的前半部分相邻差均为 1,后半部分相邻差从 k 开始逐渐递减到 1,这样从 1 到 k 的差值均出现一次,对应的列表即为:
[1, 2, \cdots, n-k, n, n-k+1, n-1, n-k+2, \cdots]
代码
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: vector<int> constructArray(int n, int k){ vector<int> answer; for (int i = 1; i < n - k; ++i) { answer.push_back(i); } for (int i = n - k, j = n; i <= j; ++i, --j) { answer.push_back(i); if (i != j) { answer.push_back(j); } } return answer; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicint[] constructArray(int n, int k) { int[] answer = newint[n]; intidx=0; for (inti=1; i < n - k; ++i) { answer[idx] = i; ++idx; } for (inti= n - k, j = n; i <= j; ++i, --j) { answer[idx] = i; ++idx; if (i != j) { answer[idx] = j; ++idx; } } return answer; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicint[] ConstructArray(int n, int k) { int[] answer = newint[n]; int idx = 0; for (int i = 1; i < n - k; ++i) { answer[idx] = i; ++idx; } for (int i = n - k, j = n; i <= j; ++i, --j) { answer[idx] = i; ++idx; if (i != j) { answer[idx] = j; ++idx; } } return answer; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defconstructArray(self, n: int, k: int) -> List[int]: answer = list(range(1, n - k)) i, j = n - k, n while i <= j: answer.append(i) if i != j: answer.append(j) i, j = i + 1, j - 1 return answer
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int* constructArray(int n, int k, int* returnSize){ int *answer = (int *)malloc(sizeof(int) * n); int pos = 0; for (int i = 1; i < n - k; ++i) { answer[pos++] = i; } for (int i = n - k, j = n; i <= j; ++i, --j) { answer[pos++] = i; if (i != j) { answer[pos++] = j; } } *returnSize = n; return answer; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var constructArray = function(n, k) { const answer = newArray(n).fill(0); let idx = 0; for (let i = 1; i < n - k; ++i) { answer[idx] = i; ++idx; } for (let i = n - k, j = n; i <= j; ++i, --j) { answer[idx] = i; ++idx; if (i !== j) { answer[idx] = j; ++idx; } } return answer; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcconstructArray(n, k int) []int { ans := make([]int, 0, n) for i := 1; i < n-k; i++ { ans = append(ans, i) } for i, j := n-k, n; i <= j; i++ { ans = append(ans, i) if i != j { ans = append(ans, j) } j-- } return ans }