首页 > 其他 > 详细

LeetCode_26

时间:2019-03-09 17:41:51      阅读:176      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

解题思路:

要求删除数组中的重复元素。

定义好 [0,k)范围内为非重复元素。 定义一个变量pre记录上一个元素的值,且仅当下一个元素的值不等于pre时再更新。

代码如下:

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

 

LeetCode_26

原文:https://www.cnblogs.com/harchar/p/10502009.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!