Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  116 随笔 :: 0 文章 :: 28 评论 :: 93214 阅读

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

地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/

算法:直接看代码:

复制代码
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(n <= 1)  return n;
 5         int j = 1;
 6         for(int i = 1; i < n; ++i){
 7             if(A[i] != A[i-1]){
 8                 A[j++] = A[i];
 9             }
10         }
11         return j;
12     }
13 };
复制代码

第二题:

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

地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

算法:每个元素至少可以有两个。遍历的过程中统计每一个元素出现的次数,然后最多留下其中的两个。代码:

复制代码
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(!A || n <= 2)  return n;
 5         int j = 0;
 6         int i = 0;
 7         while(i < n){
 8             int count = 1;
 9             while(i + count < n && A[i+count] == A[i]){
10                 ++count;
11             }
12             A[j++] = A[i++];
13             --count;
14             if(count){
15                 A[j++] = A[i++];
16                 --count;
17             }
18             i += count;
19         }
20         return j;
21     }
22 };
复制代码

 

posted on 2014-09-03 22:28  Boostable  阅读(128)  评论(0)    收藏  举报
编辑推荐:
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
· 智能桌面机器人:使用 .NET 为树莓派开发 Wifi 配网功能
阅读排行:
· 一则复杂 SQL 改写后有感
· 接口被刷百万QPS,怎么防?
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一个开源免费、功能丰富的 WPF 自定义控件资源库
· 提升Avalonia UI质感,跨平台图标库选型实践
点击右上角即可分享
微信分享提示