簡體   English   中英

從排序數組邏輯中刪除重復項在 C# 中拋出異常以獲得正確答案

[英]Remove Duplicates From Sorted Array Logic Throwing Exception For Correct Answer in C#

我用兩種相似的語言回答了一個名為“從排序數組中刪除重復項”的 LeetCode 問題,以准備不同的面試。 我的 Java 解決方案被標記為正確,但 C# 解決方案引發運行時錯誤,並顯示消息Unhandled exception. System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. Unhandled exception. System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

我在 Java 中的正確解決方案如下:

public int removeDuplicates(int[] nums) {
    
        int pointer1 = 0;
        
        for (int pointer2 = 1; pointer2 < nums.length; pointer2++) {
            if (nums[pointer1] != nums[pointer2]) {
                pointer1++;
                nums[pointer1] = nums[pointer2];
            }
        }
        
        return pointer1 + 1;
    }

我在 C# 中的錯誤解決方案如下:

public int RemoveDuplicates(int[] nums)
        {
            int pointer1 = 0;

            for (int pointer2 = 1; pointer2 < nums.Length; pointer2++)
            {
                if (nums[pointer1] != nums[pointer2])
                {
                    pointer1++;
                    nums[pointer1] = nums[pointer2];
                }
            }

            return pointer1 + 1;
        }

要求是就地執行此操作,因此我避免使用額外的內存。 當我在循環范圍內指定長度時,我無法理解為什么長度超出數組范圍。 此外,僅在嘗試 C# 解決方案時才會拋出此錯誤。 我正在努力改進 C#,並想知道我的實現有什么問題。 感謝您的任何和所有反饋。

拋出的可能不是您的代碼,因為您從中獲得的唯一 OutOfRange 異常是“索引越界”,而不是“偏移和長度越界”。 無論調用您的代碼拋出。

它可能會嘗試在空數組或 null 上運行您的方法,嘗試在nums.Length == 0nums == null時返回 0 或 -1。

(來自評論:是的,當一個空數組作為參數傳遞時,它預計為 0。需要的檢查是:

if (nums.Length == 0)
    return 0;

)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM