Leetcode题解系列(一):数组[T80]

注意:本篇是本系列第一篇文章,本系列文章并不是对某一个算法专题,如数组,进行全面性的总结与延伸讨论,而是记录某个专题下相关题目的解题思路,争取从多个题解中总结出一般规律,掌握正确的思考方法,学会快速正确的解决问题。

Leetcode 80.Remove Duplicates from Sorted Array II

题目描述

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.

思路分析

理解要求

数组已排序,保留两个相同元素移除多余的,返回新数组的长度,在原数组修改

思路

从头开始遍历数组,依据要求从第一个位置开始将保留元素按序重排。关键是剔除条件:将当前元素与len-2元素比较,若相等,说明已经存在两个,则剔除判断下一个元素;如果不相等,则放入对应位置,再判断下一个元素。

举例图解

如,数组为[1,1,1,2,2,3],
举例图解

完整代码(C++)

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = 0;
for (int i = 0; i < nums.size(); i++) {
if (len < 2 || nums[i] > nums[len - 2]) {
nums[len++] = nums[i];
}
}
return len;

}
};

posted @ 2019-05-17 11:08  Nolan24  Views(131)  Comments(0Edit  收藏  举报