LeetCode 26. Remove Duplicates from Sorted Array

https://leetcode.com/problems/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.

  • 数组array处理题。由于题目不管对数组的操作,可以有两种方法。一种是in-place算法,覆盖数组前n个为不重复数字;另一种是erase删除重复节点。
  • 原地算法_百度百科
    • https://baike.baidu.com/item/原地算法
    • 一个原地算法(in-place algorithm)是一种使用小的,固定数量的额外之空间来转换资料的算法。当算法执行时,输入的资料通常会被要输出的部份覆盖掉。
  • vector::erase - C++ Reference
    • http://www.cplusplus.com/reference/vector/vector/erase/
 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 }
View Code
1
2
Program ended with exit code: 0
View Result

 

posted on 2018-01-30 13:09  浩然119  阅读(150)  评论(0编辑  收藏  举报