代码改变世界

Remove Duplicates from Sorted Array

2014-08-08 21:20  valerlina  阅读(143)  评论(0编辑  收藏  举报

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

数组A删除所有值为elem的元素,保证A的前length个元素都没有elem,返回length。

idea:使用双指针,一个从前往后找elem的元素,一个从后往前找非elem的元素,然后交换二者,出错点是一些边界条件。

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         int i=0,j=n-1;
 5         int length=n;
 6         while(i<n)
 7         {
 8             while(j>=0&&A[j]==elem)
 9             {
10                 length--;
11                 j--;
12             }
13                 
14             if (A[i]==elem&&j>i)
15             {
16               A[i]=A[j];
17               i++;
18               j--;
19               length--;
20             }
21             else
22             {
23                 i++;
24             }
25         }
26         return length;
27     }
28 };