LeetCode算法题之Remove Duplicates from Sorted Array

来源:互联网 发布:慈溪市编程成绩 编辑:程序博客网 时间:2024/06/06 13:25

问题描述:

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




0 0
原创粉丝点击