【Leetcode】442. Find All Duplicates in an Array
2017-02-25 12:03
32 查看
442. Find All Duplicates in an Array
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:
Subscribe to see which companies asked this question.
题目简述:
输入一个数组,数组中元素满足 1 ≤ a[i] ≤ n
,输入数组中出现两次的元素。
要求:不能使用额外空间,时间复杂度O(n)
思路简述:
step 1 想到利用数组中索引的信息,按顺序读取数组,假设本轮读取到的数字为A,如果A = -1 或者 A指向自己位置则跳过。
step2 访问数字A对应位置的元素,如果该元素与A相同,将该位置元素置-1,表示A出现过两次。返回step 1。
step3 重新访问数组,-1元素对应的索引+1就是出现两次的元素。
代码:
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for(int i=0;i<nums.length;){
int temp = 0;
if(nums[i] <=0 || nums[i]-1 == i){
i++;
}else if(nums[nums[i]-1]!=-1 &&nums[nums[i]-1] != nums[i] ){
temp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] =temp;
}else{
nums[nums[i]-1] = -1;
i++;
}
}
for(int i=0;i<nums.length;i++){
if(nums[i] == -1){
res.add(i+1);
}
}
return res;
}
}
运行结果:
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]
Subscribe to see which companies asked this question.
题目简述:
输入一个数组,数组中元素满足 1 ≤ a[i] ≤ n
,输入数组中出现两次的元素。
要求:不能使用额外空间,时间复杂度O(n)
思路简述:
step 1 想到利用数组中索引的信息,按顺序读取数组,假设本轮读取到的数字为A,如果A = -1 或者 A指向自己位置则跳过。
step2 访问数字A对应位置的元素,如果该元素与A相同,将该位置元素置-1,表示A出现过两次。返回step 1。
step3 重新访问数组,-1元素对应的索引+1就是出现两次的元素。
代码:
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for(int i=0;i<nums.length;){
int temp = 0;
if(nums[i] <=0 || nums[i]-1 == i){
i++;
}else if(nums[nums[i]-1]!=-1 &&nums[nums[i]-1] != nums[i] ){
temp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] =temp;
}else{
nums[nums[i]-1] = -1;
i++;
}
}
for(int i=0;i<nums.length;i++){
if(nums[i] == -1){
res.add(i+1);
}
}
return res;
}
}
运行结果:
相关文章推荐
- [LeetCode] Combinations、Subsets、Subsets II
- Leetcode: Decode Ways
- LeetCode Swap Nodes in Pairs
- 【leetcode】Pascal's Triangle && Pascal's Triangle II
- leetcode:Valid Palindrome【Python版】
- [LeetCode] Sudoku Solver
- LeetCode189:Rotate Array
- LeetCode 133 Clone Graph
- LeetCode之“动态规划”:Maximum Subarray
- leetcode HouseRobber Dp Code
- leetcode_Permutations II
- Leetcode || Remove Duplicates from Sorted Array
- Java [Leetcode 202]Happy Number
- leetcode:Merge k Sorted Lists 【Java】
- LeetCode Reverse Integer
- leetcode_c++:Merge_Intervals(056)
- LeetCode-Design Twitter
- [Leetcode] Move Zeroes
- Leetcode-264. Ugly Number II
- Leetcode 409. Longest PalindromeJAVA语言