C#中能否原地修改数组?不创建新数组实现元素增删
Great question—this is a common point of confusion because of how C# arrays work under the hood. Let’s break it down clearly:
First, the hard truth about C# arrays
In C#, arrays have a fixed length once they’re initialized. You can’t directly "remove" or "add" elements to change the array’s Length property—this is baked into the array’s core design. So if you’re asking whether you can make the array physically smaller or larger without creating a new array object, the answer is no.
But you can simulate in-place removal (like the LeetCode problem requires)
What LeetCode’s "Remove Duplicates from Sorted Array" asks for is logical in-place modification: you don’t need to change the array’s actual length, just overwrite elements in the original array so that the first N elements are the desired result (with no duplicates), and return N as the count of valid elements. This counts as O(1) space because you’re not allocating any new array memory.
Here’s a classic example of how to do this with the two-pointer technique:
public int RemoveDuplicates(int[] nums) { if (nums.Length == 0) return 0; int slowPointer = 0; for (int fastPointer = 1; fastPointer < nums.Length; fastPointer++) { // When we find a unique element, move it to the next position in the valid section if (nums[fastPointer] != nums[slowPointer]) { slowPointer++; nums[slowPointer] = nums[fastPointer]; } } // The number of valid elements is slowPointer + 1 return slowPointer + 1; }
In this code:
- We’re not creating any new arrays—all modifications happen directly on the original
numsarray. - The elements after
slowPointer + 1are still in the array, but we just ignore them (since the return value tells the caller how many elements to consider valid).
What about methods like Array.Resize?
You might have seen Array.Resize<T>(ref T[] array, int newSize), but this doesn’t actually modify the original array in-place. It creates a new array with the specified size, copies elements from the original array to the new one, and then updates the array reference to point to the new array. The original array gets marked for garbage collection, so this doesn’t count as O(1) space.
Why do most answers recommend using List<T>?
List<T> is a wrapper around an array that handles resizing automatically. Its Remove method shifts elements to fill the gap left by the removed item, but it still uses extra space (for the underlying array’s capacity buffer) and doesn’t strictly meet the O(1) space requirement for problems like the LeetCode one.
To sum up:
- You can’t change a C# array’s physical length in-place.
- You can modify the array’s content in-place to create a logical subset of valid elements, which is exactly what problems requiring O(1) space are asking for.
内容的提问来源于stack exchange,提问作者Adam Elders

