LeetCode-- Remove Duplicates from Sorted Array (数组操作)

题目Remove Duplicates from Sorted Array

 Total Accepted: 16392 Total Submissions: 51515My Submissions

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].

Have you been asked this question in an interview? 


解题思路:

首先读清题意,题目很简单,删除数组(sorted)中重复的元素,然后返回唯一元素的大小。A数组要变化。

分两种情况:

1》若数族大小为0/1。 数组A 不变,返回0/1。

2》 若数组大小大于1。用count记录新数组元素A的末尾的下一个index,若a[i] != a[i-1], 则把 a[i]的值赋给count位置上(a[count] = a[i] )。

例如数组元素为 1, 2 2, 2 2, 3, 3, 4。 此时count=2,表示A的下标2前面有两个不同的元素,若 A[5]=3,A[4]=2, 则到A[5] != A[4]时,将A[5]的只赋给A[count]上,然后count++。详细如下面代码


记住:

1. 当自己面对问题想解题思路的时候,要依靠自己的逻辑思维来”证明/保证”算法的可靠性,不能依靠调试/测试来发现代码的中的bug或逻辑错误。

2. 能一次性写出没有逻辑错误,能够work的代码 是编程能力的体现,也是Google 或 Facebook等大公司面试的必备。




源代码“

java源代码(两个等价代码,不同的视角):

Perspective:(让元素后面的元素与前面的元素相比)

    public int removeDuplicates(int[] A) {
    	if(A.length ==0){
    		return 0;
    	}
    	int count=1;
    	for(int i=1; i<A.length; ++i){
    		if(A[i] != A[i-1]){ //注意这行代码
    			A[count]=A[i];
    			count++;
    		}
    	}
    	return count;
    }

Perspective: 让前面的元素与后面的元素相比(这个视角在下面相关的一道题中很有用)。

    public int removeDuplicates(int[] A) {
    	if(A.length ==0){
    		return 0;
    	}
    	int count=1;
    	for(int i=1; i<A.length; ++i){
    		if(A[count-1] != A[i]){ //注意这行代码
    			A[count]=A[i];
    			count++;
    		}
    	}
    	return count;
    }



相关题目:

LeetCode--Remove Duplicates from Sorted Array II

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值