leecode-Remove Duplicates from Sorted Array

来源:互联网 发布:软件安装在系统盘 编辑:程序博客网 时间:2024/06/05 02:27

1. 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 A = [1,1,2] ,
Your function should return length = 2, and A is now [1,2] .

代码

#include<iostream>#include<vector>using namespace std;class solution {public:    int removeDuplicates(vector<int> &nums) {        if (nums.empty()) return 0;        int index = 1;        for (int i = 1; i< nums.size(); i++) {            if (nums[i] != nums[index - 1])                nums[index++] = nums[i];        }        return index;    }};void main(){    vector<int> nums = { 1,1,2,2,4 };    for (int i = 0; i< nums.size(); i++)        cout << nums[i] << " ";    cout << endl;    solution sol;    int length = sol.removeDuplicates(nums);    for (int i = 0; i < length; i++)        cout << nums[i] << " ";    cout << endl;}

2. Remove Duplicates from Sorted Array II

描述:Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3] , your function should
return length = 5 , and A is now [1,1,2,2,3]

class solution {public:    int removeDuplicates(vector<int> &nums) {        if (nums.size() <= 2) return nums.size();        int index = 2;        for (int i = 2; i< nums.size(); i++) {            if (nums[i] != nums[index - 2])                nums[index++] = nums[i];        }        return index;    }};
0 0
原创粉丝点击