LeetCode @ 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 A = [1,1,2],

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

//来源于soulmachine: 
//1.双指针一个for内解决;	2.表象是去重,实质上是把题目要求的元素归入新数组
//         index
//[  1,  1,  1,  1,  1,  1,  2,  2,  2,  3]
//           i

public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length==0)
            return 0;
        int index=0;//第一个指针定义在for外,用来表征新Array长度,也是新Array的index
        for(int i=1;i<A.length;i++){//第二个指针定义在for内,指向待验证是否相同的元素
            if (A[index]!=A[i])
                A[++index]=A[i];//index先跳至要被覆盖的元素,后覆盖之,注意不同于follow up题目;
        }
        return index+1;//截取in-place新Array
    }
}


1.时间O(n),空间O(1)

2.关键在于比较不同,AC各种testcase

------------------------------------------------

问题思考:

1.其实类似于长度变短的String,可否用smilence以下原则?(不行,因为结合follow up题目,不确定新array size变大变小)

d.对于要求in-place的删除或修改,可以用两个int变量分别记录新index与原index,观察:如果改动后size增大,则先resize(int),再倒序赋值;反之,则先顺序赋值,再resize.

2.面试时思考过程要合理的解释出来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值