https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
public class Solution {
public IList<int> FindDisappearedNumbers(int[] nums) {
List<int> result = new List<int>();
int numsLength = nums.Length;
for (int i = 0; i < numsLength; i++)
{
int index = Math.Abs(nums[i]) - 1;
if (nums[index] > 0)
{
nums[index] = -nums[index];
}
}
for (int i = 0; i < numsLength; i++)
{
if (nums[i] > 0)
{
result.Add(i + 1);
}
}
return result;
}
}
Runtime: 308 ms, faster than 98.68%
of C# online submissions.
Memory Usage: 42.6 MB, less than 50.0%
of C# online submissions.
Time Complexity: O(n)
Space Complextiy: O(n)
這題主要是在說,我給你一個 size = n 的 array
裡面應該要有 1 ~ n 的數字,不一定是排序過的 array
請幫我找出漏掉的數字並回傳 List<int>
一開始我本來用 Dictionary 去紀錄消失的數字,但效果不彰
所以改用 nums array
本身去紀錄,這樣效能也比較好
負數
,nums[index] = -nums[index]
Math.Abs
取 絕對值
,再去找 index沒有被標記成負數
的 index,就是消失
的數字,所以將index+1
Add 到 result 即可
如果看文字敘述不是很明確的話,可以看下面的示意圖。
以上就是這次 LeetCode 刷題的分享啦!
如果其它人有更棒的想法及意見,請留言或寄信(t4730@yahoo.com.tw) 給我。
那我們就下回見囉