- To finish with
O(1)extra space? We’d better use the orignal array.
- It’s a method called
- Because all number are between
[1,n], and the length of nums is
n. So the correct order should be
nums[i] = i - 1.
nums[i]is not in the correct place, which means
nums[i] !== nums[nums[i] - 1]. We should swap them.
- After swapping, don’t move
i, we need to do this again on the new
- What about
nums[i] == nums[nums[i] - 1]:
i !== nums[i] - 1, it means we’ve met a num that appears twice.
i === nums[i] - 1, it means the num is in the correct place, let’s
Given an integer array
nums of length
n where all the integers of
nums are in the range
[1, n] and each integer appears once or twice, return an array of all the integers that appears
You must write an algorithm that runs in
O(n) time and uses only
constant extra space.
Input: nums = [4,3,2,7,8,2,3,1]