【Leetcode】【Easy】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].

 

解题思路1:

数组中相似的元素,不能像链表一样删除重构。可以使用两个index,一个用来遍历原数组,另一个用来标记新构造数组的尾部/长度。

所谓新构造数组,只是在原数组的空间上做填充,不会使用新的空间。

代码:

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n==0) 
 5             return n;
 6             
 7         int newArrayLen = 1;
 8         
 9         for (int i=0; i<n-1; i++) {
10             if (A[i] != A[i+1]) {
11                 A[newArrayLen++] = A[i+1];
12             }
13         }
14         
15         return newArrayLen;
16     }
17 };

 

附录-

 

posted @ 2014-12-02 13:13  胡潇  阅读(146)  评论(0编辑  收藏  举报