LeetCode 26.Remove Duplicates from Sorted Array

来源:互联网 发布:java迭代器遍历list 编辑:程序博客网 时间:2024/05/17 05:12

LeetCode 26.Remove Duplicates from Sorted Array

Description:

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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.


分析:

注意这道题加了限制,在O(1)空间复杂度实现,且该数组已排序
可以弄一个变量temp,初始置为0,循环判断是否和相邻的数相等,若不等,则更新temp的值(+1),同时nums[temp]更新为相邻的一个数(后面的数),最后返回temp+1则是该结果。


代码如下:

#include <iostream>#include <algorithm>#include <vector>#include <set>using namespace std;class Solution {public:    int removeDuplicates(vector<int>& nums) {        if (nums.size() == 0) return 0;        int temp = 0;        for (int i = 1; i < nums.size(); i++) {            if (nums[temp] != nums[i]) {                temp++;                nums[temp] = nums[i];            }        }        return temp + 1;    }};int main() {    Solution s;    vector<int> nums;    int n;    cin >> n;    int t;    for (int i = 0; i < n; i++) {        cin >> t;        nums.push_back(t);    }    cout << s.removeDuplicates(nums) << endl;    return 0;}