1. 程式人生 > >[Leetcode] Remove duplicates from sorted array 從已排序的數組中刪除重復元素

[Leetcode] Remove duplicates from sorted array 從已排序的數組中刪除重復元素

all 一個 with const style 思路 leet class ould

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 A =[1,1,2],

Your function should return length =2, and A is now[1,2].

題意:除去重復的元素,若有重復只保留一個,返回長度。

思路:遍歷數組,用不同的,覆蓋相同的。過程:保存第一個元素的下標lo。遇到相等不管,繼續遍歷,遇到不等的,則將該值賦給lo的下一個,反復這樣。代碼如下:

 1 class Solution
 2 {   
 3 public:
 4     int removeDuplicates(int A[],int n)
 5     {
 6         if(n<=0)    return 0;
 7         int lo=0;
 8         for(int i=1;i<=n-1;++i)
 9         {
10 if(A[lo] !=A[i]) 11 A[++lo]=A[i]; 12 } 13 return lo+1; 14 } 15 };

思路相同,另一種寫法:

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) 
 4     {
 5         if(n<2) return n;
 6         int count=1;
 7         int flag=0;
 8         for
(int i=0;i<n;++i) 9 { 10 if(A[flag] !=A[i]) 11 { 12 A[++flag]=A[i]; 13 count++; 14 } 15 } 16 return count; 17 } 18 };

[Leetcode] Remove duplicates from sorted array 從已排序的數組中刪除重復元素