[leetcode][array]remove dulplicates 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].

solution:

①需要返回重构的A的长度②检验返回长度内,A是否已经没有重复(长度外数据不考虑)

·条件②表明,我们不用考虑长度外的数据,只需要保证长度内的数据无重复且sorted(有序)即可,因此长度内的数据遇到重复时可以使用长度外的不重复数据进行覆盖

·两个参数,一个i用来从前向后循环数组,一个index(从0开始)用来记录最后一个没有重复的数字的位置。当index位置后面出现不重复的数字,将index值加一并附新的不重复值,当index后面全部重复出现,则index+1就是不重复数组长度。

·考虑空集和只有一个元素的数组(可以整合进去)

code:

<span style="color:#333333;">public class Solution {
    public int removeDuplicates(int[] A) {
        int index = 0;
		int length = A.length;
		if (</span><span style="color:#ff0000;">length == 0</span><span style="color:#333333;">) {
			return 0;
		}else {
			for (int i = 1; i < length; i++) {
				if (A[i] == A[index]) {
					</span><span style="color:#ff0000;">continue;</span><span style="color:#333333;">
				}else {
					</span><span style="color:#ff0000;">index++;
					A[index] = A[i];	//直接覆盖</span><span style="color:#333333;">
				}
			}
			return index+1;
		}
    }
}</span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值