编写一个算法来返回一个数组,使来自1..n的每个数字k正好出现两次,并且距离其副本是k个距离 [英] Write an algorithm to return an array such that every number k from 1..n is occurring exactly twice and is k distance apart from its replica
问题描述
对于给定的整数n> = 3,返回一个大小为2n的数组,使得从1到n的每个数字k都是发生恰好两次,每个数字,重复的距离等于该数字。
功能签名:
int * buildArray(int n)
对于n = 3:
3,1,2,1,3,2
号码 2
:第1位3和第2位6,所以距离6 - 3 - 1 = 2.
号码 3
:第一个 3
在位置1和第二个 3
在位置5,所以距离5 - 1 - 1 = 3。
对于n = 4:
4,1,3,1,2,4,3,2
这是一个Langford的问题/序列。
有一个关于SO已经实现了同样的问题。
Langford序列实现Haskell或C
This question was asked in an interview.
For a given integer n >= 3 return an array of size 2n such that every number k from 1 to n is occurring exactly twice and every number and its repetition is separated by a distance equal to the number.
Function signature:
int* buildArray(int n)
For example, for n = 3:
3, 1, 2, 1, 3, 2
Number 2
: 1st position 3 and 2nd position 6, so distance 6 - 3 - 1 = 2.
Number 3
: First 3
at position 1 and 2nd 3
at position 5, so distance 5 - 1 - 1 = 3.
For n = 4:
4, 1, 3, 1, 2, 4, 3, 2
It's a Langford's problem/sequence.
There is a topic about the same problem on SO with implementation already. Langford sequence implementation Haskell or C
这篇关于编写一个算法来返回一个数组,使来自1..n的每个数字k正好出现两次,并且距离其副本是k个距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!