LeetCode 26

摘要:
注意:您只能就地工作,不能使用其他阵列。
一、问题描述

Description:

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

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.

Note:

Do not allocate extra space for another array, you must do this in place with constant memory.

给一个有序数组,原地移除重复的元素,并返回新数组的长度。

注意:只能原地工作,不能使用额外的数组。


二、解题报告

由于输入的是有序数组,在遍历过程中,我们只需要判断是否与前面的重复即可。

代码:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty()) 
            return 0;
        int count = 1;
        int pre = nums[0];
        vector<int>::iterator beg = nums.begin();
        for(++beg; beg!=nums.end(); ) {   // 从第二个开始
            if(*beg == pre)               // 重复,移除
                beg = nums.erase(beg);
            else                          // 不重复,更新pre
            {
                pre = *beg;
                ++beg;
            }
        }
        return nums.size();
    }
};





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


免责声明:文章转载自《LeetCode 26》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇easyui datagrid设置fit: true后,页面显示不全的情况easyui combobox下拉框 多选赋值及选中下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

[LeetCode] 1026. Maximum Difference Between Node and Ancestor

Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. A node A is an ancesto...

IDEA2020.1使用LeetCode插件运行并调试本地样例

环境: idea2020.1 插件: LeetCode-editor 6.7 一、IDEA安装LeetCode插件 安装完成重启idea 打开插件 URL可以选择国服和世界服。LoginName和Password填自己的用户名和密码即可。 需要配置的选项为: TempFilePath: 自己保存代码的包的位置 CodeFileName: $!veloc...

leetcode编程框架——在IDE上模拟leetcode环境

1、为什么写这个为了用IDE!,这样不同的大题,复制粘贴就完事,真正帮你节约大把时间来思考题目。 import sys # 这里写解决问题的代码,和LeetCode就完全一样了 def solve(arr): pass if __name__ == '__main__': # 接收输入的逻辑,这里先把输入接收过来, 两种选择input()和sy...

工具推荐--刷LeetCode的神器

本文首发于微信公众号:【坂本先生】,文章地址为:https://mp.weixin.qq.com/s/vHv5hO8nils_g2VSKwu1Cg如有转载请标明出处 今天给大家安利一款快速刷LeetCode的工具,能够让你专注于题目本身,而不是如何去建立题目。这个工具是基于IDEA的,名叫LeetCode Editor,它的官方GitHub地址为:http...

最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。示例 1:输入: ["flower","flow","flight"]输出: "fl"示例 2:输入: ["dog","racecar","car"]输出: ""解释: 输入不存在公共前缀。说明:所有输入只包含小写字母 a-z 。 方法一: 水平扫描法: 思路首先,我们将...

leetcode 36 有效的数独 哈希表 unordered_set unordersd_map 保存状态 leetcode 37 解数独

leetcode 36 感觉就是遍历。 保存好状态,就是各行各列还有各分区divide的情况 用数组做。 空间小时间大 class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { int row[9][9]={...