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

就是去掉數組中重複的數字,只保留一個,返回處理後數組中的元素個數,要求不能再設置一個數組!

解題思路:

很簡單,不多說!算法複雜度O(n)!

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n == 0)
            return 0;
        int start = 0;
        int key = A[0];
        int i = 0;
        while(i < n)
        {
            if (A[i] != key)
            {
                A[start++] = key;
                key = A[i];
            }
            i++;
        }
        A[start++] = key;
        return start;
    }
};




發佈了47 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章