在数组中交换索引和价值

发布于 2025-02-08 13:43:16 字数 354 浏览 6 评论 0原文

假设我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2025-02-15 13:43:16

如果问题是关于JavaScript的,则可以简单地使用 indexof()方法。
在您的情况下:

first_array.indexOf(55); // it will return index of **55** in first_array

if the question is about javascript, you can simply use indexOf() method.
in your case:

first_array.indexOf(55); // it will return index of **55** in first_array
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文