简体   繁体   English

通过索引的距离更改数组的值(c)

[英]Changing the values of array by the distance of the indexes (c)

I'm having hard time with this one: I need to write a function in C that recieving a binary array and his size, and the function should calculate and replace the current values with the distance (by indexes) of each 1 to the closest 0. for example: if the function recieve that array {1,1,0,1,1,1,0,1} then the new values of the array should be {2,1,0,1,2,1,0,1} . 我很难用这个:我需要在C中编写一个接收二进制数组及其大小的函数,函数应该计算并用每个1到最近的距离(通过索引)替换当前值例如:如果函数接收到数组{1,1,0,1,1,1,0,1}则数组的新值应为{2,1,0,1,2,1,0,1} It is known that the input has atleast 1 zero. 众所周知,输入至少为零。

So the first step I tought about was to locate pair of zeros (or just 1 if there is only 1) and set them as 2 indexes ( z1 , z2 ). 所以我想要的第一步是找到一对零(如果只有一个则只有1)并将它们设置为2个索引( z1z2 )。 Then I set another index i that check everytime which zero is the closest to him (absolute value) and then the diffrence between i and z1 or z2 would be the new value. 然后我设置另一个索引i ,每次检查哪个零最接近他(绝对值),然后iz1z2之间的差异将是新值。

I have the plan but things are not going exactly as I planned. 我有计划,但事情并没有完全符合我的计划。 Basicly I deleted the code (it wasn't good anyway) so I would appreciate any help. 基本上我删除了代码(不管怎样都不好)所以我很感激任何帮助。 thanks! 谢谢!

This problem is based on two things 这个问题基于两件事

  • Keep an array left[i] which has the distance of nearest 0 from index i from left to right. 保持一个数组left[i] ,其距离索引i的距离最近为0

  • Keep an array right[i] which has the distance of nearest 0 from index i from right to left. 保持一个数组right[i] ,其距离索引i的距离最近为0

Both can be calculate in single loop iteration. 两者都可以在单循环迭代中计算。 O(n) . O(n)

  • Then for each position get the minimum value of left[i] and right[i] . 然后为每个位置获得left[i]right[i]的最小值。 That will be the answer for 1 staying in position i . 这将是1留在i位置的答案。

Overall the time complexity is O(n) . 总的来说,时间复杂度是O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM