(有序数组中移除重复元素)Remove Duplicates from Sorted Array

题目:

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array A =[1,1,1,2,2,3],
Your function should return length =5, and A is now[1,1,2,2,3].

思路

两个指针,i用于遍历A数组,index指向B数组中下一个可能的合法位置,初始设置为index=2。
比较A[i]和B[index-2],若相等,说明i指向的元素不合法,此时不应该把A[i]加入到B中,i++;
若不想等,说明i指向的元素合法,应该设置B[index] = A[i],index++,指向下一个可能合法的位置。

java代码

public int removeDuplicates2(int A[]) {
        int n = A.length;
        int[] B = new int[n];/
        if (n < 3) // 最多含有2个元素,一定满足题意
            return n;
        B[0] = A[0];
        B[1] = A[1];
        int index = 2; // 可能不合法的位置
        for (int i = 2; i < n; i++) {
            if (A[i] != B[index - 2])
                B[index++] = A[i];
        }
        for(int i=0;i<n;i++)
            A[i] = B[i];
        return index;
    }
发布了113 篇原创文章 · 获赞 19 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章