C# - Modify an array in place, without creating another array in memory

为君一笑 提交于 2021-02-19 06:06:10

问题


In C#, is it possible to remove an element from an array in place?

Of course, there are a ton of questions on SO about removing items from an array. Every answer either uses a List or creates another array with the new values. However, I'd like to know if it's even possible to modify an array in place (deleting or adding elements) in C#.

In the easy LeetCode question "Remove Duplicates from Sorted Array", you are restricted to the same array, you cannot create a new array in memory (O(1) space in memory). Is this possible using C#? I can't come up with a solution that does not create another array.


回答1:


In C#, is it possible to remove an element from an array in place?

No, by definition of array. Arrays are fixed-length. You can, however, track the number of "elements you care about" within the array (an integer) and remove elements by copying following elements down to their prior index & decrementing this counter.

You'd then have derived an Array List (List<T> in .NET).

In the easy LeetCode question "Remove Duplicates from Sorted Array", you are restricted to the same array, you cannot create a new array in memory (O(1) space in memory). Is this possible using C#? I can't come up with a solution that does not create another array.

The question wants you to modify the provided array with your solution, then return the length of the subset of the array (starting at index 0) filled with unique values.

A solution in Java is available here: https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/ - you can change two letters (length to Length twice) to get it compiling in C#.

I'll paste that here anyway:

int RemoveDuplicates(int[] nums) {
    if (nums.Length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.Length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}


来源:https://stackoverflow.com/questions/50033837/c-sharp-modify-an-array-in-place-without-creating-another-array-in-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!