diff options
author | Jack Sangdahl <[email protected]> | 2025-04-09 11:32:32 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-04-09 11:32:32 -0600 |
commit | 85b7b78bbfd84e323374ebe7dbf20d5be696ac36 (patch) | |
tree | e0a102cfe8f37c2bc75c523c68aa1b86aee5140f | |
parent | 792ebab379f6802b0d63c67eae2e8772066ffe28 (diff) | |
download | leetcode-85b7b78bbfd84e323374ebe7dbf20d5be696ac36.tar.gz leetcode-85b7b78bbfd84e323374ebe7dbf20d5be696ac36.zip |
667. beautiful arrangement 2
-rw-r--r-- | beautiful_arrangement2.c | 38 | ||||
-rw-r--r-- | beautiful_arrangement2.py | 36 |
2 files changed, 74 insertions, 0 deletions
diff --git a/beautiful_arrangement2.c b/beautiful_arrangement2.c new file mode 100644 index 0000000..37e2dcb --- /dev/null +++ b/beautiful_arrangement2.c @@ -0,0 +1,38 @@ +// 667. Beautiful Arrangement II +#include "leetcode.h" + +/* + * given two integers 'n' and 'k', construct a list 'answer' that contains 'n' + * different positive integers ranging from 1 to 'n' and obeys the following + * requirement: suppose this list is 'answer = [a1, a2, a3, ..., an]', the the + * list '[a1 - a2, a2 - a3, ..., an-1 - an]' has exactly 'k' distinct integers. + * return the list 'answer'. if there are multiple valid answers, return any of + * them. + */ + +int *constructArray(int n, int k, int *returnSize) { + *returnSize = n; + int *ans = (int *)malloc(n * sizeof(int)); + int left = 1, right = n; + for (int i = 0; i < n; i++) { + if (k > 1) { + ans[i] = (k & 1) ? left++ : right--; + k--; + } else + ans[i] = left++; + } + return ans; +} + +int main() { + int rs1, *ca1 = constructArray(3, 1, &rs1); + int rs2, *ca2 = constructArray(3, 2, &rs2); + for (int i = 0; i < rs1; i++) + printf("%d ", ca1[i]); // expect: 1 2 3 + printf("\n"); + for (int i = 0; i < rs2; i++) + printf("%d ", ca2[i]); // expect: 1 3 2 + printf("\n"); + free(ca1); + free(ca2); +} diff --git a/beautiful_arrangement2.py b/beautiful_arrangement2.py new file mode 100644 index 0000000..9bdfd1a --- /dev/null +++ b/beautiful_arrangement2.py @@ -0,0 +1,36 @@ +# 667. Beautiful Arrangement II + +""" +given two integers 'n' and 'k', construct a list 'answer' that contains 'n' +different positive integers ranging from 1 to 'n' and obeys the following +requirement: suppose this list is 'answer = [a1, a2, a3, ..., an]', the the +list '[a1 - a2, a2 - a3, ..., an-1 - an]' has exactly 'k' distinct integers. +return the list 'answer'. if there are multiple valid answers, return any of +them. +""" + + +class Solution(object): + def constructArray(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[int] + """ + ans, left, right = [0] * n, 1, k + 1 + for i in range(k + 1): + if i & 1: + ans[i] = right + right -= 1 + else: + ans[i] = left + left += 1 + for i in range(k + 1, n): + ans[i] = i + 1 + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.constructArray(3, 1)) + print(obj.constructArray(3, 2)) |