在数组中交换索引和价值
假设我有一个n个元素,每个元素代表0和n-1之间的唯一整数。假设我想找到给定整数的索引,我可以在数组中循环循环并在找到数字时返回索引。由于这是低效的,因此我可以制作第二个数组,因此对于first_array [10] = 55
,我们将获得second_array [55] = 10
。
现在,假设我不想创建第二个数组,我想在就位进行开关。是否有一种聪明的方法可以做到这一点,聪明,意味着没有额外的分配,没有疯狂的深层递归,也没有在整个阵列N时进行搜索?这种操作有名字吗?我觉得这是一个必须已经解决的问题,但我无法想象它可以叫什么。
编辑:这是一个关于算法的问题,无论编程语言如何,答案,即算法,都应起作用。
Let's say I have an array of N elements, each element representing a unique integer between 0 and N-1. Let's say I want to find the index of a given integer, I can loop through the array and return the index when I find the number. Since this is inefficient, I could make a second array, so that for first_array[10] = 55
we'd obtain second_array[55] = 10
.
Now let's say that I don't want to create a second array and I want to do the switch in-place. Is there a clever way to do this, clever meaning no extra allocation, no crazy deep recursion and no searching through the whole array N times? Does this kind of operation have a name? I feel like this is a problem that must have already been solved but I can't imagine what it could be called.
Edit: This is a question about an algorithm, the answer, being an algorithm, should work the same regardless of the programming language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果问题是关于JavaScript的,则可以简单地使用 indexof()方法。
在您的情况下:
if the question is about javascript, you can simply use indexOf() method.
in your case: