在做leetcode的时候,发现的c#中的问题,标记一下:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2.就是说去掉数组中与给定值相同的元素,并且返回心数组长度,由于本人脑子不好使,用了很笨的办法。
public int RemoveElement(int[] nums, int val)
{
int[] temp = null;
int i = 0, j = 0, count = 0;
while (i < nums.Length)
{
if (nums[i] != val)
count++;
i++;
}//求temp的长度,如果没有这一步,则代码报nullreference的错。
temp = new int[count];
i = 0;
while (i < nums.Length)
{
if (nums[i] != val)
{
temp[j] = nums[i];
j++;
}
i++;
}
nums = temp;
return temp.Length;
}
最后发现打印传入的nums函数的时候竟然nums没有发生任何改变。。
后来才知道,就算int[]是引用类型,如果不使用关键字ref 或者
out(适用场景不同)全是作为值传递的,在方法内部会拷贝一个副本,方法结束之后,销毁这个副本。