LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結:Remove Duplicates from Sorted Array

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

這道題的要求是在有序數組中重複資料刪除元素,使每個數字出現且只出現1次,並返回數組的新的長度。要求:不允許申請額外空間,即要求恒定的空間複雜度。

這道題的思路就是採用兩個指標l和r,l記錄不重複元素的位置,r從l的下一個開始遍曆數組,如果r位置的數字等於l位置的數字,說明該數字重複出現,不予處理;如果r位置的數字不等於l位置的數字,說明該數字沒有重複,需要放到l的下一位置,並使l加1。

時間複雜度:O(n)

空間複雜度:O(1)

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

轉載請說明出處:LeetCode --- 26. Remove Duplicates from Sorted Array

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.