htdwade的博客

记录个人工作学习中的心得

LeetCode题解 —— 26.Remove Duplicates from Sorted Array

题目描述

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

解题思想

考虑两种解决方案:
* 采用双指针的思想,一前一后扫描来解决这个问题,前面的指针用于遍历数组元素,后面的指针用于维护非冗余数组的右边界。
* 扫描有序数组,统计数组中重复数字的个数,用数组大小减去重复数字的个数即可得解。

解题代码

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int removeDuplicates1(vector<int>& nums) {
        if(nums.size() < 2)
            return nums.size();
        int index = 1;
        for(int i = 1; i < nums.size(); i++){
            if(nums[i] != nums[i - 1])
                nums[index++] = nums[i];
        }
        return index;
    }

    int removeDuplicates2(vector<int>& nums) {
        int count = 0;
        for(int i = 1; i < nums.size(); i++){
            if(nums[i] == nums[i - 1])
                count++;
            else
                nums[i - count] = nums[i];
        }
        return nums.size() - count;
    }
};

int main()
{
    Solution solution;
    vector<int> nums1 = {1, 1, 2};
    vector<int> nums2 = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
    cout << "测试removeDuplicates1: " << solution.removeDuplicates1(nums1) << endl;
    cout << "测试removeDuplicates2: " << solution.removeDuplicates2(nums2) << endl;
    return 0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013507678/article/details/80330314
文章标签: LeetCode 算法
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode题解 —— 26.Remove Duplicates from Sorted Array

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭