RemoveDuplicates I

问题

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.

解决方案

思路:这道题是让我们去掉数组里重复项,我们使用快慢指针来记录遍历的坐标,最开始两个指针指向第一个数,如果相同,快指针走一步,如果不同,都走一步,当快指针走完整个数组时,慢指针当前的坐标加1就是数组中不同数字的个数。


int removeDuplicates(int* nums, int numsSize)
{
	if (numsSize <= 0)
	{
		return 0;
	}

	int i = 0;
	for (int j = 0; j < numsSize; j++)
	{
		if (nums[i] != nums[j])
		{
			i++;
			nums[i] = nums[j];
		}
	}
	return i + 1;
}

猜你喜欢

转载自blog.csdn.net/qq_39478237/article/details/82760317
I