LeetCode OJ : Remove Duplicates from Sorted Array

来源:互联网 发布:光盘数据恢复 编辑:程序博客网 时间:2024/06/16 23:32
Remove Duplicates from Sorted Array 

链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

题解:

给一个有序数组,让你除去重复的数字和除去后的长度。比如A=[1,1,2],返回A=[1,2],长度为2。要求使用常数空间。

维护两次指针a,b,a指向不重复数组的最后一个数字,b指向已处理的部门的最后一个数字。当A[a]!=A[b]时,说明又找到一个新的数字,把A[b]覆盖A[a+1],同时++a。记得特判空串和长度为1的情况。

代码:

public class Solution {    public int removeDuplicates(int[] A) {        if(A==null||A.length==0) return 0;        if(A.length==1) return 1;        int a=0,b=0;        int len=A.length;        for(;b<len;){            for(;b<len&&A[a]==A[b];++b);            if(b<len&&A[a]!=A[b]){                ++a;                A[a]=A[b];            }        }        return a+1;    }}
来源:http://blog.csdn.net/acm_ted/article/details/44496509

0 0
原创粉丝点击