[LeetCode]Remove Duplicates from Sorted Array

来源:互联网 发布:Mac版本好玩的网络游戏 编辑:程序博客网 时间:2024/06/12 18:00

题目:

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

来源:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/


思路:

因为是有序的数组,只要前后指针,一次遍历就行。

C++ AC代码:

class Solution {public:    int removeDuplicates(int A[], int n) {        if( n < 2)    return n;int i=0, j=1;while( i < n && j < n ){    if( A[i] == A[j] )    j++;else    A[++i] = A[j++];}return i+1;    }};


运行时间 116ms

0 0
原创粉丝点击