版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Testiness_Wind/article/details/82346064
题目
C#中的数组在声明时必须指定长度,且无法动态的删除数组中的元素,只可以替换,列表可以动态的修改长度。
数组
将数组重新排序,重复元素后移,返回不重复的元素的数量。
空间复杂度 O(1)
public static int[] nums1 = new int[10] { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
private static int i = 0;
public static int removeRepeat1Array(int[] nums)
{
if (nums.Length == 0) return 0;
for (int j = 1; j < nums.Length; j++)
{
if (nums[j] != nums[i])
{
i++;
nums[i] = nums[j];
}
}
i++;
return i;
}
列表
将数组重新排序,重复元素后移,删除重复元素,返回列表长度。
空间复杂度 O(1)
public static List<int> nums2 = new List<int> { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
private static int i = 0;
public static int removeRepeat1List(List<int> nums)
{
if (nums.Count == 0) return 0;
for (int j = 1; j < nums.Count; j++)
{
if (nums[j] != nums[i])
{
i++;
nums[i] = nums[j];
}
}
i++;
nums.RemoveRange(i, nums.Count - i);
return nums.Count;
}