26. Remove Duplicates from Sorted Array

来源:互联网 发布:苹果应用下载软件 编辑:程序博客网 时间:2024/05/16 15:57

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.

Subscribe to see which companies asked this question.

先翻译题目:移除给定有序数组中的重复元素,然后返回数组长度;不可额外创建数组,只允许使用当前数组空间;

我的思路是设置两个游标,i=0,j=1;因为这是一个有序数组,所以必定后面的元素大于或者等于前面的元素;

然后从j=1与i=0相比较,如果相等则j++,又与i=0相比较,直到不等为止,然后i++,将此时的j对应的元素赋值给i;

由于最后i指向的是最后一个元素的位置,所以数组长度还需要加一,i++,返回;

这里做的时候一开始没考虑如果是个空数组怎样,所以后来加上了对空数组的判断;

以下为代码示例:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0)
        return 0;
        int i=0;
        int j=1;
        for(j=1;j<nums.size();j++){
            if(nums[i]==nums[j]){
                continue;
            }
            i++;
            nums[i]=nums[j];
        }
        i++;
        return i;
    }
};


0 0
原创粉丝点击