首页 > 代码库 > 448. Find All Numbers Disappeared in an Array
448. 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]
分析
n位整数数组本应包含1~n所有数,实际缺少了其中一些,找出这些缺少的数。
限制条件:不占用额外空间(除返回的list以外),时间复杂度O(n)
解答
解法1:把数组下标+1当做一个"新数组",出现的则将对应下标+1标记为负数,未标记的下标+1则是未出现的数(18ms)
遍历数组,遇到4则将数组中第4个数(下标为3)修改为负数
再次遍历数组,若第m个数(下标为m-1)没有被修改为负数,意味着m是数组中缺少的数
例:
1 2 3 4 5 6 7 8 (下标+1)
4 3 2 7 8 2 3 1
-4 -3 -2 -7 8 2 -3 -1
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> list = new ArrayList<Integer>(); 4 for (int i = 0; i < nums.length; i++){ 5 nums[Math.abs(nums[i])-1] = - Math.abs(nums[Math.abs(nums[i])-1]); 6 //最内部绝对值:遍历到已被标记为负数的数时,要用其绝对值来寻找下标 7 //最外部绝对值:重复出现的数,下标已被标记过一次,再直接求相反数会又变为正,需先绝对值再求相反数 8 } 9 for (int i = 0; i < nums.length; i++){ 10 if(nums[i] > 0){ 11 list.add(i + 1); 12 } 13 } 14 return list; 15 } 16 }
解法2:解法1中的第5行拆开写(17ms√)
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> list = 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 nums[index] = - nums[index]; 8 } 9 for (int i = 0; i < nums.length; i++){ 10 if(nums[i] > 0){ 11 list.add(i + 1); 12 } 13 } 14 return list; 15 } 16 }
448. Find All Numbers Disappeared in an Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。