LeetCode刷题实战442:数组中重复的数据
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 twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
示例
输入:
[4,3,2,7,8,2,3,1]
输出:
[2,3]
解题
class Solution {
public ListfindDuplicates(int[] nums) {
Listres = new ArrayList<>();
for(int i = 0;i < nums.length;++i){
int index = Math.abs(nums[i])-1;
if(nums[index] < 0){
res.add(index+1);
}else if(nums[index] > 0){
nums[index] *= -1;
}
}
return res;
}
}
评论