LeetCode 26. Remove Duplicates from Sorted Array

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.

  • 數組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
相關文章
相關標籤/搜索