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

Leetcode: Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

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

Output:
[5,6]

 

 1 public class Solution {
 2     public List<Integer> findDisappearedNumbers(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) res.add(i+1);
14         }
15         return res;
16     }
17 }

 

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