好的,我会买这不是功课.这是解决方案.假设k = 3,N = 5
开始:
ar[0] = 0
ar[1] = 0
ar[2] = 0
ar[3] = 0
ar[4] = 0
生成一个随机数.假设它是2.我们现在需要存储两位信息:
>“2”是第一个随机数.
>“2”被采取.
所以我们这样做:
ar[0] = 2
ar[1] = 0
ar[2] = 10 // 10 is any number that's larger than N.
ar[3] = 0
ar[4] = 0
下一个号码:4
ar[0] = 2
ar[1] = 4
ar[2] = 10 // taken
ar[3] = 0
ar[4] = 10 // taken
下一个号码:2
ar[2] >= 10 thus taken, try another number
下一个号码:1
ar[0] = 2
ar[1] = 14 // added 10 to signify it's taken
ar[2] = 11 // added 1 as it's the current number
ar[3] = 0
ar[4] = 10 // taken
完成.
现在,迭代数组,并从大于10的所有内容中减去10.你将最终得到
ar[0] = 2
ar[1] = 4
ar[2] = 1
ar[3] = 0
ar[4] = 0
一个警告 – 这假设随机数在[1..N]范围内.如果它们是[0..N-1],你必须调整一下.