You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中array = anotherArray[anotherArray[i]]语句的执行逻辑及示例解析

拆解数组嵌套索引赋值逻辑:ans[i] = nums[nums[i]]的计算过程

先看你提供的代码:

public static int[] buildArray(int[] nums) {
    int[] ans = new int[nums.length];
    for (int i = 0; i < nums.length; i++) {
        ans[i] = nums[nums[i]];
    }
    return ans;
}

这段代码的核心逻辑是:对每个索引i,先取nums数组中i位置的元素,把这个元素当作新的索引,再去nums数组中取对应位置的元素,最后把这个值放到ans数组的i位置。

我们用输入nums = {0, 2, 1, 5, 3, 4}逐个索引计算:

  • 当i=0时:
    nums[0] = 0 → 用0作为新索引取nums[0] = 0 → ans[0] = 0
  • 当i=1时:
    nums[1] = 2 → 用2作为新索引取nums[2] = 1 → ans[1] = 1
  • 当i=2时:
    nums[2] = 1 → 用1作为新索引取nums[1] = 2 → ans[2] = 2
  • 当i=3时:
    nums[3] = 5 → 用5作为新索引取nums[5] = 4 → ans[3] = 4
  • 当i=4时:
    nums[4] = 3 → 用3作为新索引取nums[3] = 5 → ans[4] = 5
  • 当i=5时:
    nums[5] = 4 → 用4作为新索引取nums[4] = 3 → ans[5] = 3

把这些结果按顺序排列,就得到了输出数组[0,1,2,4,5,3]。

简单来说,这就是一层「索引映射」:每个位置的结果由原数组的索引嵌套取值得到,相当于把原数组的元素当作新的索引,再做一次取值操作。

内容的提问来源于stack exchange,提问作者Artokrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:30:40