leetcode之 Remove Duplicates from Sorted Array

来源:互联网 发布:哪个贷款软件最靠谱 编辑:程序博客网 时间:2024/05/06 06:34

题目:

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

解答:

找到第一个比当前大的数,放到当前的后面,如此下去即可,注意下一次寻找的时候可以不用从当前开始寻找,直接从上一次找到的位置开始就可以,因为数组已经是sorted的了,这样复杂度是O(n),从当前开始寻找复杂度是O(n^2),然而在跑的时间上却没什么区别,看来leetcode的测试数据并没有那种很刁钻的

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int size = nums.size();
        if(size == 0)
            return 0;
        if(size == 1)
            return 1;
        int pos = 0;
        //int end = size - 1;
        int findStart = pos + 1;
        while(true)
        {
            bool find = false;
            for(int j = findStart;j < size;++j)
            {
                if(nums[j] > nums[pos])
                {
                    find = true;
                    int t = nums[j];
                    nums[j] = nums[pos + 1];
                    nums[pos + 1] = t;
                    pos++;
                    findStart = j + 1;
                }
            }
            if(!find)
                break;
        }
        return pos + 1;
    }
};

0 0
原创粉丝点击