Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
1 | Input: |
1 暴力
想不出来O(1)空间的了
1 | class Solution { |
2 原地标记
思路借鉴于: hou-yong-sheng (leetcode-cn)
利用nums[i] 属于 [1,n]的特点, 每一个值都可以对应一个下标. 这里使用值i对应i-1下标
如果读到一个值i, 就把nums[i-1]的值置为负数. 如果再次读到i时, 检查nums[i-1]是不是为负数, 如果是的话, 说明前面肯定出现过i, 重复!!
1 | class Solution { |