LeetCode之Remove Duplicates from Sorted Array

1、题目

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.

 

2、实现

代码一实现:
public class Solution {
    public int removeDuplicates(int[] a) {
        if (null == a) {
    return 0;
    }
    int length = a.length;
   // if (length > 0)
   // a[0] = a[0];
    int newLen = 1;
    for (int i = 1; i < length; ++i) {
    if (a[i] != a[i - 1]) {
    a[newLen++] = a[i];
    }
    }
    return newLen;
    }
}

代码二实现:

public  int removeDuplicates1(int[] a) {
if (a == null || a.length == 0) {
return 0;
}
        int length = a.length;
for (int i = 0; i < length - 1; ++i) {
if (a[i] == a[i + 1]) {
for (int j = i + 1; j < length - 1; j++) {
a[j] = a[j + 1];
}
i--;
length--;
}
}
return length;
}

 

3、总结

方法一总结:我们不能重新申请空间,在原基础数组改,我们知道只要说到“连续数字”,我么应该马上想到这个数字和前面的数字相同,我们在原始数组上,第一个元素就是新数组的第一个元素,后面如果新元素和前面的元素不一样,我们就把这个后面的元素添加在新数组的末尾。
方法二总结:
记得进行i--和length--
(0)

相关推荐