442. Find All Duplicates in an Array
題目網址:https://leetcode.cn/problems/find-all-duplicates-in-an-array/
題意:給一有
n個數的 arraynums, 每個元素值皆在[1, n], 且每個元素可能出現 一次 or 兩次, 求所有出現兩次的數。注意:使用 $O(n)$ time 和 $O(1)$ space 的演算法

Solution:
想法:將數字乘以負號來標記我們看到的數字的 index, 然後遍歷
nums元素, 若nums[i] > 0, 代表數字i + 1出現過兩次(類似 448. Find All Numbers Disappeared in an Array)e.g.
[1, 1, 2]➔[1, -1, 2],nums[i - 1]決定數字i出現的次數
class Solution { |
- time:$O(n)$ ➔ 遍歷
nums - space:$O(1)$ ➔ 扣除返回的 array, 只需常數空間
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論