leetcode 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.

题目要求,输入一个大小为n的数组,数组中包含着值为1~n的元素,有的值出现过一次,有的值出现过两次,而咱们须要找到没有在数组中出现的1~n中的值,并以List形式返回这些值。
这道题额外要求了咱们须要在O(n)的时间复杂度下解决这个问题,同时不使用额外空间(返回的list不算作额外空间)数组

Example:
Input:[4,3,2,7,8,2,3,1]
Output:[5,6]app

思路

  • 在遍历每个值的时候,咱们都找到这个值按照元素1~n顺序排序时应该在的位置。
  • 若是这个位置的值为正(意味着咱们尚未对这个元素进行过操做),咱们将这个位置的元素的值取负。
  • 在整个遍历结束后,没有取负的值的索引,就能够对应到没有在数组出现过的值

解法

public List<Integer> findDisappearedNumbers(int[] nums) {
             List<Integer> res = new ArrayList<Integer>();
        
        for(int num : nums){
            int val = Math.abs(num)-1;
            if(nums[val] > 0){
                nums[val] = - nums[val];
            }
        }
        for(int i =0;i<nums.length;i++){
            if(nums[i] > 0){
                res.add(i+1);
            }
        }
        return res;   
    }
相关文章
相关标签/搜索