活跃农民
- 积分
- 315
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-5-26
- 最后登录
- 1970-1-1
|
第二天打卡
加上我对first missing positive的notes
O(n) time and O(1) space
we first find if 1 exists in this list, if it doesn't, simply return 1
when we are iterating the first time, we can turn all the numbers <= 0 and > n to 1
since that we know if 1 exists, setting these numbers to 1 will be safe
reason we still set numbers > n to 1 is because this list can only contain 1...n elements
which means if a number is > n, our return integer will be in 1...n by pidgeon hole principle
in the next loop, we negate the nums[value] to indicate that we have seen this number
remember to use abs(value)-1 because
1. the current value can be negative because some other number has negated this value
2. -1 because array starts from 0 to n-1 but our values are from 1 to n
in the last iteration, we set the starting point to 2, and see if any point from low-1
is negative. if so, return low
we will return low outside of the while loop in case 2 or n+1 is the answer |
|