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

Leetcode: Remove Duplicates from Sorted Array

时间:2015-03-20 00:06:15      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目:
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++参考代码:

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#参考代码:

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参考代码:

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参考代码:

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;
    }
}

Leetcode: Remove Duplicates from Sorted Array

标签:leetcode

原文地址:http://blog.csdn.net/theonegis/article/details/44465855

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