使用 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 次测试,但随后给了我这个错误:

未处理的异常。 System.IndexOutOfRangeException:索引为 超出数组范围。在 Solution.SingleNumber(Int32[] nums) 在 DriverSolution.Helper(Int32[] param_1) 在 驱动程序.Main(String[] args)

我怀疑这可能是因为

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

c# arrays logic
1个回答
1
投票

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.