码迷,mamicode.com
首页 > 其他好文 > 详细

Q5: Remove Duplicates from Sorted Array

时间:2015-03-21 21:16:20      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

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

解决原理:

(若输入数组无序,则先对数组进行排序,则相同值相邻)

两个游标len,i

0~len是元素不重复的子数组,即len是目标子数组的最后一个元素的索引

游标i遍历数组

若A[i]!=A[len],则为目标子数组增添一个元素

代码:

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

 

Q5: Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/ISeeIC/p/4356125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!