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

Leetcode | Remove Duplicates from Sorted Array I && II

时间:2014-05-19 12:10:41      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

Remove Duplicates from Sorted Array I

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

这道题很简单,就是维护一个新数组的尾指针,tail,把去重后的数放到A[tail]就行,最终返回tail。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n <= 1) return n;
 5         int tail = 0, v;
 6         
 7         for (int i = 0; i < n;) {
 8             v = A[i];
 9             for (i++; i < n && A[i] == v; ++i);
10             A[tail++] = v;
11         }
12         return tail;
13     }
14 };
bubuko.com,布布扣

 

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

同上,区别在于,去重的时候,允许有两个重复的数;多的话还是略掉。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n <= 1) return n;
 5         int tail = 0, v, j = 0;
 6         
 7         for (int i = 0; i < n;) {
 8             v = A[i];
 9             for (j = 0; j < 2 && i + j < n && A[i + j] == v; ++j) {
10                 A[tail++] = v;
11             }
12             for (i += j; i < n && A[i] == v; ++i);
13         }
14         return tail;
15     }
16 };
bubuko.com,布布扣

哈哈,Leetcode第一遍至此结束了!!!!cheers!

bubuko.com,布布扣

Leetcode | Remove Duplicates from Sorted Array I && II,布布扣,bubuko.com

Leetcode | Remove Duplicates from Sorted Array I && II

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/linyx/p/3735563.html

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