LeetCode 26. Remove Duplicates from Sorted 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 being1
and2
respectively. It doesn't matter what you leave beyond the new length.
大致意思就是给定一个已排好序的数组,删除数组中的重复元素并返回删除后的数组大小,删除操作必须在原数组中进行,不允许我们另建一个数组。
因为返回值只有新数组的大小,开始我以为只要统计出数组中的不重复元素个数并返回即可AC,有点native了。本题要求我们原址操作,这样即可验证我们是否删除了数组中的重复元素并得到正确的新数组,所以光统计不重复元素个数是不行的。
这里设置两个指针i和j,i指向新数组的最后一个元素,j用来遍历原数组,当nums[j] == num[i]
,直接递增j来跳过重复元素;当nums[j] != num[i]
,先递增i更新新数组的尾指针,把nums[j]赋值到新数组的尾部,再递增j访问下一个元素即可。这样仅需遍历数组一遍即可得出新数组及其大小。
上述算法的时间复杂度为O(n),空间复杂度为O(1)
代码如下:
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0)
return 0;
int i = 0; // 新数组最后一个元素的指针
for (int j = 1; j < nums.length; j++)
{
if (nums[j] != nums[i])
nums[++i] = nums[j];
}
return i + 1;
}
}
LeetCode 27. Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2
, with the first two elements of nums being 2
.
大致意思就是给定一个数组和一个值,删除数组中等于该值的元素并返回删除后的数组大小,删除操作必须在原数组中进行,不允许我们另建一个数组。
该题目与上面的题目类似,不多说,上代码
public class Solution {
public int removeElement(int[] nums, int val) {
int i = -1; // 新数组最后一个元素的指针
for(int j = 0; j < nums.length; j++)
{
if(nums[j] != val)
nums[++i] = nums[j];
}
return i + 1;
}
}
网友评论