LeetCode 442. Find All Duplicates in an Array

本文提供两种解决LeetCode上查找数组中所有重复数字的方法。第一种方法通过标记数组元素来查找重复项,时间复杂度为O(n),空间复杂度为O(1)。第二种方法则通过交换元素至正确位置来找出重复项,同样保持O(n)的时间复杂度及O(1)的空间复杂度。

原题链接在这里: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: 

 1 public class Solution {
 2     public List<Integer> findDuplicates(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         for(int i = 0; i<nums.length; i++){
 9             int index = Math.abs(nums[i])-1;
10             if(nums[index] < 0){
11                 res.add(index + 1);
12             }else{
13                 nums[index] = -nums[index];
14             }
15         }
16         return res;
17     }
18 }

可以吧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:

 1 class Solution {
 2     public List<Integer> findDuplicates(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         for(int i = 0; i<nums.length; i++){
 5             if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){
 6                 swap(nums, i, nums[i]-1);
 7                 i--;
 8             }      
 9         }
10         
11         for(int i = 0; i<nums.length; i++){
12             if(nums[i] != i+1){
13                 res.add(nums[i]);
14             }
15         }
16         
17         return res;
18     }
19     
20     private void swap(int [] nums, int i, int j){
21         int temp = nums[i];
22         nums[i] = nums[j];
23         nums[j] = temp;
24     }
25 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6241994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值