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.
Solution:
这道题的技巧是数组已经排序了,所有的duplicated的元素都是相邻的。因此可以使用two pointers的思路,用一个i指针遍历所有元素的同时,用另一个j指针指向当前被拿来作比较的元素,如果i指向的元素等于j指向的元素,则什么都不做;如果i指向的元素不等于j指向的元素,意味着从此以后i指向的元素永远不会再与j指向的相等。因此可以将i指向的元素放在j指向元素的后一个位置并向后移动j指针(被拿来作比较的元素变成原来的后一个元素了)。
public class Solution
{
public int removeDuplicates(int[] nums)
{
int j = 0;
for(int i = 0; i < nums.length; i ++)
{
if(nums[j] != nums[i])
{
nums[j + 1] = nums[i];
j ++;
}
}
return j + 1;
}
}
网友评论