26. Remove Duplicates from Sorted Array
来源:互联网 发布:软件开发立项申请表 编辑:程序博客网 时间:2024/06/05 12:49
题目:Remove Duplicates from Sorted Array
原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
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.
给出一个排序好的数组,删除数组中的重复元素,并且返回最新的值。
不允许新建额外的数组,使用常数级的内存。
例,给出数组[1,1,2]
返回长度为2,数组中元素为[1,2]
设now和cnt,now表示当前扫描的元素的下标,cnt表示下标为0到cnt - 1部分是对应下标0到now - 1部分已经整理好的结果。
让now和cnt同时向后扫描,如果nums[now] != nums[cnt - 1],说明当前元素与前面的是不重合的,将其覆盖到前面去,即nums[cnt++] = nums[now++],如果nums[now] == nums[cnt - 1],说明这是一个重复的元素,让now继续往下扫描即可。
代码如下:
class Solution {public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); if(len <= 1) return len; int now = 0, cnt = 0; while(now < len) { if(now == 0) { cnt++; now++; }else{ if(nums[now] == nums[cnt - 1]) { while(now < len && nums[now] == nums[cnt - 1]) { now++; } if(now < len) { nums[cnt] = nums[now]; cnt++; now++; } }else{ nums[cnt] = nums[now]; now++; cnt++; } } } nums.erase(nums.begin() + cnt, nums.end()); return cnt; }};
- [LeetCode]26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode --- 26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- [Leetcode] 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- 【leetcode】 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- [leetCode]26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array LeetCode
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- oracle查询重复数据并删除掉多余部分
- Android应用安装覆盖问题
- 《响应式Web设计实践》学习笔记
- javascript BOM与DOM
- 读《互联网3.0 云脑物联网创造DT新世界》有感
- 26. Remove Duplicates from Sorted Array
- Java集合类(大公司面试喜欢问的)
- Error inflating class android.support.design.widget.CollapsingToolbarLayout
- C++第三课-之二(类和对象)
- 关于异步加载获取网络图片的
- Eclipse中10个最有用的快捷键组合
- [置顶] 2016Android某公司面试题
- poj 1039 Pipe (线段相交判定)
- scala中class与Object