LeetCode 记录(c#版)
- 26. Remove Duplicates from Sorted Array(Tag—-Array)
原题:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
求已排序数组的长度:
遍历长度为n的数组(时间复杂度O(n)), 由于是已排序数组,每次遇到nums[i]!=nums[j],计数器i++
并且使得:nums[i]=nums[j]
空间复杂度0(1);
代码
:
public int RemoveDuplicates(int[] nums)
{
if (nums.Length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.Length; j++)
{
if (nums[i] != nums[j])
{
i++;
nums[i] = nums[j];
}
}
return i+1;
}
脚注
reference:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/