You need to enable JavaScript to run this app. 如何返回数组中第二个不同值对应的索引?
优惠活动
大模型
产品
解决方案
定价
更多

如何返回数组中第二个不同值对应的索引?

Ruby 实现获取数组第二个不同值的索引

核心思路

以数组第一个元素为基准值,遍历数组找到第一个和基准值不相等的元素,返回其索引即可。如果数组所有元素都相同则返回nil,也可自定义默认返回值。

代码实现

简洁写法

arr = [10, 10, 10, 10, 10, 15, 12, 12, 3]
result = arr.index { |item| item != arr.first }
puts result # 输出 5

大数组优化写法

无需遍历全数组,找到目标值就终止遍历,性能更高:

def get_second_diff_idx(arr)
  return nil if arr.length < 2
  base = arr[0]
  arr.each_with_index do |val, idx|
    return idx if val != base
  end
  nil
end

# 测试调用
arr = [10, 10, 10, 10, 10, 15, 12, 12, 3]
puts get_second_diff_idx(arr) # 输出 5

边界场景处理

  • 数组元素全部相同:返回nil,可按需调整为返回-1等自定义值
  • 数组长度小于2:返回nil
  • 前两个元素就不同:直接返回索引1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 17:15:03