LeetCode Find All Duplicates in an Array

原题链接在这里:https://leetcode.com/problems/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:

Input:
[4,3,2,7,8,2,3,1] Output:
[2,3]

题解:

类似Find All Numbers Disappeared in an Array. iterate nums array时把nums[Math.abs(nums[i]-1)]标负,但需要先检查是否已经标过负了。若是说明是出现过一次. 把index+1添加到res中.

Time Complexity: O(nums.length). Space: O(1).

AC Java:

 public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if(nums == null || nums.length == 0){
return res;
} for(int i = 0; i<nums.length; i++){
int index = Math.abs(nums[i])-1;
if(nums[index] < 0){
res.add(index + 1);
}else{
nums[index] = -nums[index];
}
}
return res;
}
}

可以吧num[i] swap到对应的index = nums[i]-1上面.

第二遍iterate时如果nums[i] !=i+1. nums[i]就是duplicate的. 加入res中.

Time Complexity: O(n). Space: O(1), regardless res.

AC Java:

 class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for(int i = 0; i<nums.length; i++){
if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){
swap(nums, i, nums[i]-1);
i--;
}
} for(int i = 0; i<nums.length; i++){
if(nums[i] != i+1){
res.add(nums[i]);
}
} return res;
} private void swap(int [] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
上一篇:UITableView使用的一些技巧


下一篇:使用Skaffold一键将项目发布到Kubernetes