Remove Duplicates from Sorted Array Solutions in C++
Number 26
Difficulty Easy
Acceptance 45.2%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/// Author : Hao Chen// Date : 2014-06-22class Solution {public:int removeDuplicates(int A[], int n) {if (n<=1) return n;int pos=0;for(int i=0; i<n-1; i++){if (A[i]!=A[i+1]){A[++pos] = A[i+1];}}return pos+1;}};
C++ solution by pezy/LeetCode
class Solution {public:int removeDuplicates(int A[], int n) {if (n < 2) return n;int size = 1;for (int i = 1; i != n; ++i)if (A[i-1] != A[i])A[size++] = A[i];return size;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-array//// Author : liuyubobobo/// Time : 2016-12-06#include <iostream>#include <vector>#include <cassert>#include <stdexcept>using namespace std;/// Two pointers/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:int removeDuplicates(vector<int>& nums) {if(nums.size() == 0)return 0;int res = 1;int index = nextDifferentCharacterIndex(nums, 1);int i = 1;while(index < nums.size()){res ++;nums[i++] = nums[index];index = nextDifferentCharacterIndex(nums, index + 1);}return res;}private:int nextDifferentCharacterIndex(const vector<int> &nums, int p){for( ; p < nums.size() ; p ++ )if( nums[p] != nums[p - 1] )break;return p;}};int main() {vector<int> nums1 = {1, 1, 2};cout << Solution().removeDuplicates(nums1) << endl;return 0;}