C#-在适当的位置修改数组,而无需在内存中创建另一个数组 [英] C# - Modify an array in place, without creating another array in memory

查看:51
本文介绍了C#-在适当的位置修改数组,而无需在内存中创建另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,是否可以从数组中删除某个元素?

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

当然,关于从数组中删除项目还有很多问题.每个答案要么使用列表,要么使用新值创建另一个数组.但是,我想知道是否甚至可以在C#中修改数组(删除或添加元素).

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#.

在简单的LeetCode问题从已排序的数组中删除重复项"中,您只能使用同一数组,因此无法在内存中创建新的数组(内存中的O(1)空间).使用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.

推荐答案

在C#中,是否可以从数组中删除某个元素?

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.

然后,您将派生数组列表(.NET中的List< T>).

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

在简单的LeetCode问题从已排序的数组中删除重复项"中,您只能使用同一数组,因此无法在内存中创建新的数组(内存中的O(1)空间).使用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.

该问题希望您使用解决方案修改提供的数组,然后返回填充有唯一值的数组子集的长度(从索引0开始).

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.

此处提供Java解决方案: https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/-您可以更改两个字母(将 length 更改为 Length 两次)以获取它使用C#编译.

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#.

我还是要粘贴到这里:

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;
}

这篇关于C#-在适当的位置修改数组,而无需在内存中创建另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆