[LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)
來源:程序員人生 發(fā)布時間:2015-04-30 08:34:20 閱讀次數(shù):3921次
索引:[LeetCode] Leetcode 題解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
026. Remove Duplicates from Sorted Array (Easy)
鏈接:
題目:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
代碼(github):https://github.com/illuz/leetcode
題意:
給1個有序數(shù)列,刪重復(fù)的元素。
分析:
如果可以開1個數(shù)組來存就非常容易。但是這題不讓你用過剩的空間。
不過也不難,只要保護1個新的坐標就好了。
用 C++ 的 STL 可以只要1句話:用 unique
實現(xiàn)功能,用 distance
計算大小。
Java 和 Python 的寫法都和 C++ 的1樣,這里就不寫出來了。
代碼:
C++: (摹擬)
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (!n)
return 0;
int ret = 1;
for (int i = 1; i < n; i++)
if (A[i] != A[i - 1])
A[ret++] = A[i];
return ret;
}
};
C++: (STL)
class Solution {
public:
int removeDuplicates(int A[], int n) {
return distance(A, unique(A, A + n));
}
};
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈