https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ios
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:app
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.
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <vector> 11 using namespace std; 12 13 class Solution { 14 public: 15 // erase 16 int removeDuplicates(vector<int>& nums) { 17 if (nums.empty()) return 0; 18 19 for (auto i = 0; i < nums.size() - 1; i ++) { 20 while (nums.at(i) == nums.at(i + 1) && i + 1 < nums.size()) { 21 nums.erase(nums.begin() + i + 1); 22 } 23 } 24 25 return nums.size(); 26 } 27 28 // In-place algorithm 29 int removeDuplicates1(vector<int>& nums) { 30 if (nums.empty()) return 0; 31 32 int i = 0; 33 34 for (int j = 1; j < nums.size(); j ++) { 35 if (nums.at(j) != nums.at(i)) { 36 ++ i; 37 nums.at(i) = nums.at(j); 38 } 39 } 40 41 return i + 1; 42 } 43 }; 44 45 int main(int argc, char* argv[]) 46 { 47 Solution testSolution; 48 49 vector<int> sample {1,1,2}; 50 51 int size = testSolution.removeDuplicates1(sample); 52 53 for (auto i = 0; i < size; i ++) { 54 cout << sample.at(i) << endl; 55 } 56 57 return 0; 58 }
1 2 Program ended with exit code: 0