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;   
    }
相關文章
相關標籤/搜索