c# 使用 Array.FindIndex 时索引超出范围

问题描述 投票:0回答:1

我目前正在尝试解决 Leetcode 问题(我是一名初学者)。

这就是问题所在: 给定一个非空整数数组 nums,除了一个之外,每个元素都出现两次。找到那个单一的。

您必须实现具有线性运行时复杂度的解决方案,并且仅使用恒定的额外空间。

我的“解决方案”:


public class Solution {
    public int SingleNumber(int[] nums) {
        int[] nums2 = new int[nums.Length];  
       
        if (nums.Length == 1) {
            return nums[0]; 
        }
        for (int i = 0; i < nums.Length; i++) {
            if (!nums2.Contains(nums[i])) {
            nums2[i] = nums[i];
             
            } else {
            var x =  Array.IndexOf(nums2, nums[i]);
                 nums[x] = 0;
                nums[i] = 0;
            }
        }
       
        var index = Array.FindIndex(nums, value => value != 0);
             return nums[index];
        
       
      
        
        
    }
}

它通过了 5 次测试,但随后给了我这个错误:

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
At Solution.SingleNumber(Int32[] nums)
At __DriverSolution__.__Helper__(Int32[] param_1)
At __Driver__.Main(String[] args)

我怀疑这可能是因为 Array.FindIndex,我读到如果找不到值它将返回 -1。然而我想知道,这种情况怎么可能发生,因为总是有一个值在原始数组中出现两次,或者我的代码中是否存在其他逻辑缺陷?

谢谢

我尝试使用 ChatGPT 向我解释该问题,但失败了。

c# arrays logic
1个回答
0
投票

Xor
是这个问题的标准解决方案:直觉是,如果我们
xor
数组中的项,那么重复项将相互抵消,因为
a ^ a == 0
和 我们要一个。

Linq oneliner:

using System.Linq;

...

public class Solution {
    public int SingleNumber(int[] nums) => nums.Aggregate((s, a) => s ^ a);
}

没有 Linq 解决方案

using System.Linq;

...

public class Solution {
    public int SingleNumber(int[] nums) {
        int result = 0;

        foreach (int num in nums) 
            result ^= num;

        return result;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.