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

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<1) return 0;
        
        int first=0, second=1;
        
        while(second < n) {
            if( A[second] == A[second-1]) {
                second++;
                continue;
            }
            
            A[++first] = A[second++];
        }
        
        return first + 1;
    }
};

原文链接: https://www.cnblogs.com/xishibean/archive/2012/12/24/2951341.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Remove Duplicates from Sorted Array

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/73413

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午3:54
下一篇 2023年2月9日 下午3:56

相关推荐