LeetCode_Remove Duplicates from Sorted Array

来源:互联网 发布:java中的restfull接口 编辑:程序博客网 时间:2024/05/16 15:17

一.题目

Remove Duplicates from Sorted Array

   Total Accepted: 44643 Total Submissions: 141208My Submissions

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

Show Tags
Have you met this question in a real interview?   
Yes
   
No

Discuss


二.解题技巧

    由于数组里面的元素都是已经排好序的,因此,从第二个元素开始,只要判断这个元素是否和前面的元素相同就可以知道这个元素是否是重复的。题目要求返回不重复的元素的个数,同时,要求返回的数组的元素都是不重复的,还要是in-place的,也就是不能重新定义一个数组来保存不重复的元素,只能在原数组操作。这个问题其实也不难,我们可以设置一个变量Count来保存不重复的元素的个数,然后遍历整个数组A,如果该元素A[i]!=A[i-1]的话,将第i个元素复制到A的Count位置,也即是A[Count]=A[i],然后将Count加1.
    主要的注意点是,如果数组的元素个数小于2的话,就可以提前结束函数了。


三.实现代码

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;">int removeDuplicates(int A[], int n)  
  2. {  
  3.     if (n < 2)  
  4.     {  
  5.         return n;  
  6.     }  
  7.   
  8.     int Count = 1;  
  9.     for (int Index = 1; Index < n; Index++)  
  10.     {  
  11.         if (A[Index - 1] != A[Index])  
  12.         {  
  13.             A[Count++] = A[Index];  
  14.         }  
  15.     }  
  16.   
  17.     return Count;  
  18. }</span>  




四.体会

   这道题还是挺容易的,因为数组本身是排好序的,只要判断元素与前一个元素是否相同就知道该元素是不是重复的,同时,记录已经遍历过的元素中不重复的元素的个数的变量也同时记录了下一个不重复的元素在数组中的存放位置。根据上面的思路,就可以很快解决这道题了。


版权所有,欢迎转载,转载请注明出处,谢谢

http://blog.csdn.net/sheng_ai/article/details/43543183

0 0
原创粉丝点击