编写一个函数(例如placeAt
),该函数需要一个非负整数数组和一个非负整数索引。它应该在给定的索引处放置1,可能将其他条目移动一个位置以腾出该位置,而0表示空白位置。
- 如果所需索引处的条目为0,则用1填充。
- 否则,请在索引左侧寻找最接近的0。将条目左移一位到该0处以腾出空间,然后用1填充索引。
- 如果左侧没有0,请执行相同的操作。
- 如果两者都不可行(即,如果没有0),则返回不变的数组。
这些项目的索引为0。函数名称可以是任何您想要的。
例子:
(字母代表任何正整数。)
[a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, c, d, 0] place 2 is 0, just fill
[a, b, 0, c, d, 0] placeAt 3 // output [a, b, c, 1, d, 0] place 3 is filled, shift items left
[a, b, 0, c, d, 0] placeAt 0 // output [1, a, b, c, d, 0] place 0 is filled, can't shift left, shift items right
[a, b, 0, c, d, 0] placeAt 1 // output [a, 1, b, c, d, 0] place 1 is filled, can't shift left, shift items right
[0, a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, 0, c, d, 0] place 2 is filled, shift items left
[0, a, b, 0, c, d, 0] placeAt 4 // output [0, a, b, c, 1, d, 0] place 4 is filled, shift items left (notice you keep shifting up until a 0)
[0, 2, 0, 2] placeAt 3 // output [0, 2, 2, 1] place 3 is filled, shift items left
这是代码高尔夫挑战赛。9天后最短的参赛作品获胜。
[0, 2, 0, 2] placeAt 3
,输出合法[2, 0, 2, 1]
吗?实际需要一个称为函数的代码placeAt
吗?请注意,某些语言并不完全具有功能。“引发例外”可能也不适用于某些语言;我建议允许输出指示错误。
[2, 0, 2, 1]
这也不是合法的输出,因为您应该始终移动尽可能少的元素,并且可以根据需要命名函数。
0
怎么办?