• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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]

my solution: put integer A[i] at index A[i]-1 unless A[i] already equals i +1 or A[i] == A[A[i]-1]

later scan again if at index i, A[i] != i+1, then A[i] is a duplicate

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

 

Better solution: without destroying the input array

when find a number i, flip the number at position i-1 to negative.

if the number at position i-1 is already negative, i is the number that occurs twice.

 1 public 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             int index = Math.abs(nums[i])-1;
 6             if (nums[index] < 0) {
 7                 res.add(index+1); // index + 1 == Math.abs(nums[i])
 8             }
 9             else nums[index] = -nums[index];
10             
11         }
12         return res;
13     }
14 }

 

posted @ 2016-12-13 12:12  neverlandly  阅读(325)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3