程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> LeetCode 26 Remove Duplicates from Sorted Array(從已排序數組中移除重復元素)

LeetCode 26 Remove Duplicates from Sorted Array(從已排序數組中移除重復元素)

編輯:關於C++

翻譯

給定一個已排序的數組,刪除重復的元素,這樣每個元素只出現一次,並且返回新的數組長度。

不允許為另一個數組使用額外的空間,你必須就地以常量空間執行這個操作。

例如,
給定輸入數組為 [1,1,2]

你的函數應該返回length = 2, 其前兩個元素分別是1和2。它不關心你離開後的新長度。

原文

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 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.

代碼

class Solution {
public:
    int removeDuplicates(vector& nums) {
        if (nums.begin() == nums.end()) return 0;
        vector::iterator itor;
        for (itor = nums.begin(); itor != nums.end() && itor + 1 != nums.end(); ++itor) {
            while (*itor == *(itor + 1)) {
                nums.erase(itor + 1);
                if (itor + 1 == nums.end())
                    break;
            }
        }
        return nums.size();
    }
};

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved