Leetcode-remove duplicates in sorted array-4

Remove duplicates in sorted array

The question requires
  a sorted array to be given. You need to delete the repeated elements in the array. Each element only appears once. Return the length of the new array. The space complexity is O(1).
The idea
  is to use two subscripts, fast and slow. The fast one is used to traverse each element, and the slow one is used to record the subscript of the new array. If no element is traversed, it is compared with the number of the slow subscript. If they are not the same, then Save to the new array, the same, the fast array continues to traverse until the original array is traversed.
Code

int removeDuplicates(int* nums, int numsSize){
	int p = 0;
	if (numsSize < 2)
	{
		return numsSize;
	}
	for (int i = 1; i < numsSize; i++)
	{
		if (nums[p] != nums[i])
		{
			p++;
			nums[p] = nums[i];
		}
	}

	return p + 1;
}

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/113123811