LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結:First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example,

Given [1,2,0] return 3, and [3,4,-1,1] return 2. 

Your algorithm should run in O(n) time and uses constant space.

這道題的要求是找到數組A(未排序)中第一個缺少的正整數。要求O(n)時間複雜度。

這道題的直接思路就是先排序,然後遍曆一遍就能找到第一個缺少的正整數了。不過這樣的話,時間複雜度是O(nlogn)。

題目要求O(n)時間複雜度,那麼還能不能更快些呢?可以考慮從排序上動手腳。類似於計數排序的思路,申請個同樣大小的空數組B,然後給定數組A,把A中出現的數字放到B中對應於B下標的位置(如果該數字大小超過B的範圍,則不處理),例如把5放到B[4]裡等等。最後,再遍曆B數組,就能找到第一個缺少的正整數了。

由於上面申請的B數組和A一樣大,那麼可不可以直接用A來代替B呢?當然可以,就是在遍曆A的時候,如果數字和位置不對應,就交換到對應位置即可。

時間複雜度:O(n)

空間複雜度:O(1)

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

轉載請說明出處:LeetCode --- 41. First Missing Positive

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.