41. First Missing Positive
1 | class Solution { |
一个长度为n的数列中,如果所有正数都没缺失,那么必然是1,2,3,4...排列,且一个数a的正确位置必定是在a-1处,因此如果A[i]
不处在A[A[i] - 1]
,那么交换A[i]
和A[A[i] - 1]
让他去正确位置,由此直到所有该到正确位置的到正确位置,其中<=0和>n的数没有正确位置,所以终止。 排好位置后再遍历
手动hash?
1 | class Solution { |
引用一段解释[@triton11](https://leetcode.com/triton11/) 1
So consider an array like [1,4,3,3,3]. The length is 5, so n = 5. For each item, we are basically overwriting the spot at the index of the item with 5 + spot. So, at index 0 we have a 1, and 1%5 is 1, so we replace the item at index 1 with 5 + that item. Now our array is [1,9,3,3,3]. Next, at index 1 we have a 9, and 9%5 is 4 (notice how adding 5 didn't change the fact that we can still find the original value with % 5), so we replace the item at index 4 with 5 + that item. Our array is now [1, 9, 3, 3, 8]. Continuing, we get [1, 9, 3, 8, 8] then [1, 9, 3, 13, 8] and finally [1, 9, 3, 18, 8]. When we iterate through to find the values at the end, starting at index 1, we find that 9/5 is greater than 1, 3/5 is not greater than 1, 13/5 and 8/5 are greater than 1. Thus, since 3/5 is the first not greater than 5, we know index 2 was never used or added to, so 2 is the missing number. Feel free to comment if you have Qs or if I made any mistakes.