[抄题]:
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:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
只知道一个数重复两次就是画圈-快慢指针,很多数重复2次不知道怎么做
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
转一回:自己重复变成index重复,再转回到nums[index]重复。然后注意一下范围
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
判断重复需要:转一回:自己重复变成index重复,再转回到nums[index]重复。
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public List<Integer> findDuplicates(int[] nums) { //initialization List<Integer> result = new ArrayList<Integer>(); //for loop: get the new index, add to result if negative, change to negative for (int i = 0; i < nums.length; i++) { //get the new index int index = Math.abs(nums[i]) - 1; //add to result if negative if (nums[index] < 0) result.add(index + 1); //change to negative else nums[index] *= (-1); } //return return result; } } /* [4, 3, 2, 7, 8, 2, 3, 1] i 0 1 2 3 4 5 6 7 index 3 2 1 nums[index]*(-1) -7 -2 -3 */