LeetCode:Remove Duplicates from Sorted Array
来源:互联网 发布:第一个编程语言 编辑:程序博客网 时间:2024/06/05 01:52
一、问题描述
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.
二、思路
如果有相同的元素,删除并且计数减一。
注意:vector的函数erase在删除完元素会跳到下一个位置,所以我们必须手动跳回原来的位置,即--i;
三、代码
class Solution {public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); if(len == 0) return 0; for(int i = 0 ; i < nums.size() - 1; i++){ if(nums[i] == nums[i + 1]){ nums.erase(nums.begin() + i); --i; --len; } } return len; }};
0 0
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- [leetcode]Remove Duplicates from Sorted Array II
- Android如何解决多次fork进程的问题
- [Java]使用HttpClient实现一个简单爬虫,抓取煎蛋妹子图
- 中断与时钟机制
- FreeSwitch ESL——Event Object,Connect Object(事件套接字的事件对象及连接对象)
- Android半透明提示效果的实现
- LeetCode:Remove Duplicates from Sorted Array
- lte带宽怎么理解
- 使用HorizontalScrollView简单实现柱状图
- mysql 模糊查询(包含/存在)方法
- pt-online-schema-change注意事项 --no-check-alter
- JAVA编程基础-入门
- Linux 常用命令记录--2016年7月13日
- soa自动生成
- js 银行卡号验证