100. Remove Duplicates from Sorted Array && 101. Remove Duplicates from Sorted Array II [easy]

这两题类似,所以放在一起,先看第一题:

Description

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.

Example

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

给一个有序数组,去掉重复的部分,并返回不重复的数组长度。详细思路见代码中的注释,代码如下:

public class Solution {
    /*
     * @param nums: An ineger array
     * @return: An integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        if(nums.length==0)
        return 0;
        int cur=0;
        int pre=0;
        int n=nums.length;
        while(cur<n){
            if(nums[cur]==nums[pre]) cur++;//重复了就忽略
            else nums[++pre]=nums[cur++];//没重复,则添加到pre序列中
        }
        return pre+1;//pre即新数组的最后元素的下标,因为返回长度,所以加一
    }
}

再看另一题,有区别,个别细节不一样,但整体思路一样。代码如下:

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        if(nums.length==0){
            return 0;
        }
        if(nums.length==1){
            return 1;
        }
//区别于前一题,确保元素大于等于两个时,cur=1
int pre=0; int cur=1; int n=nums.length; while(cur<n){
//和前一题思路一样,什么时候忽略这个元素呢?只有等下标为pre和pre-1的元素都等于cur所指的元素时,说明队列中已经有两个该元素了,所以这个元素应该被忽略并覆盖,cur++
//当数组下标有减号时 例如 pre-1时,格外注意一下,数组下标不能小于0,否则会出错,即pre必须大于0
if(pre!=0&&nums[cur]==nums[pre]&&nums[cur]==nums[pre-1]){ cur++; }else{
//如果不满足if条件,说明cur所指的元素是有价值的,添加到pre队列中。 nums[
++pre]=nums[cur++]; } } return pre+1; } }

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9071056.html