leetcode--

1.题目描述

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

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 n;
        int curLen=1;
        //int curPos=0;
        int curVal=A[0];
        
        for(int i=1;i<n;i++)
        {
            if(A[i]==curVal)continue;
            else 
            {
                //如果没有移位则不必赋值
                if(curLen!=i)A[curLen]=A[i];
                curVal=A[i];
                curLen++;
            }
        }
        
        return curLen;
        
    }
};
posted @ 2013-08-23 00:01  曾见绝美的阳光  阅读(166)  评论(0编辑  收藏  举报