前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Remove Duplicates from Sorted Array

Leetcode: Remove Duplicates from Sorted Array

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 16:02:20
3480
发布2019-01-22 16:02:20
举报

题目: 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].

这道题和上一道题目比较像:Leetcode: Remove Element 都是通过定义一个伪指针,这个指针记录满足要求的数据位置,当前数据满足要求的时候(不用删除的时候)指针移动一位,最后返回这个伪指针的值。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    int removeDuplicates(int A[], int n)
    {
        if (n == 0) return 0;
        int pt = 1;
        for (int i = 1; i < n; i++)
        {
            if (A[i - 1] != A[i])
            {
                A[pt++] = A[i];
            }
        }
        return pt;
    }
};

C#参考代码:

代码语言:javascript
复制
public class Solution
{
    public int RemoveDuplicates(int[] A)
    {
        if (A.Length == 0) return 0;
        int pt = 1;
        for (int i = 1; i < A.Length; i++)
        {
            if (A[i - 1] != A[i]) A[pt++] = A[i];
        }
        return pt;
    }
}

Python参考代码:

代码语言:javascript
复制
class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        count = len(A)
        if count == 0:
            return 0
        pt = 1
        for i in range(1, count):
            if A[i - 1] != A[i]:
                A[pt] = A[i]
                pt += 1
        return pt

Java参考代码:

代码语言:javascript
复制
public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length == 0) return 0;
        int pt = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i - 1] != A[i]) {
                A[pt++] = A[i];
            }
        }
        return pt;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档