码疯窝

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

算法分析: 此题再简单不过了, 因为是sorted array, 所以只用判断相邻的两个元素是否相等就行了.

Java:

public class Solution {
    public int removeDuplicates(int[] A) {
        int l = A.length;
        int index = 1;
        if (l == 0) {
            return 0;
        }
        for (int i = 1; i < l; i++) {
            if (A[i] != A[i - 1]) {
                A[index] = A[i];
                index++;
            }
        }
        return index;
    }
}

C++:

class Solution {
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int index = 1;
        if (n == 0)
            return 0;
        for (int i = 1; i < n; i++) {
            if (A[i] != A[i - 1]) {
                A[index] = A[i];
                index++;
            }
        }
        return index;
    }
};

Python:

class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        l = len(A)
        if (l == 0):
            return 0
        n = 1
        for i in range(1, l):
            if (A[i] != A[i - 1]):
                A[n] = A[i]
                n += 1
        return n
继续查看有关 日志连载的文章

0个访客评论