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 A = [1,1,2]
,
Your function should return length = 2
, and A is
now[1,2]
.
这道题用了2个指针,一个i指向数组的值,一个newlength是指向未重复的数值的个数。
遍历数组时,当发现相同的值时,将i一直向后移动到不同值为止。同时将这个不同值移动到newLength的位置。最后返回newLength的值。
一开始在第二个循环忘记检查i值是否超出边界,导致了一次错误。
public class Solution {
public int removeDuplicates(int[] A) {
int length = A.length;
if(length == 0||length == 1)return length;
int newLength = 1;
int i = 1;
int val = A[0];
while(i<length)
{
if(A[i]!=val)
{
if(i != newLength)
{
A[newLength] = A[i];
}
val = A[i];
i++;
newLength++;
}
else
{
int temp = i;
i = i+1;
while(i<length&&A[i] == val)
{
i = i+1;
}
if(i!=length)
{
A[newLength] = A[i];
val = A[i];
i++;
newLength++;
}
}
}
return newLength;
}
}
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.
其实原理和上面一样,遍历一遍数组,把要删除的元素删除,讲后面的非删除元素向前移动。
public class Solution {
public int removeElement(int[] A, int elem) {
int length = A.length;
if(length == 0)return length;
int newLength = 0;
int i = 0;
while(i<length)
{
if(A[i]!=elem)
{
if(i!=newLength)
{
A[newLength] = A[i];
}
i++;
newLength++;
}
else
{
i++;
}
}
return newLength;
}
}
LeetCode:Remove Duplicates from Sorted Array && Remove Element,布布扣,bubuko.com
LeetCode:Remove Duplicates from Sorted Array && Remove Element
原文地址:http://www.cnblogs.com/jessiading/p/3767709.html