JavaScript solution


  • 0
    A
    1. Brutal solution:

    Use an extra length-N boolean array to find out which number in range(1, N) appeared, and which ones disappeared.

    var findDisappearedNumbers = function(nums) {
      var N = nums.length;
      var flags = new Array(N).fill(false);
      var i, result = [];
      for (i = 0; i < N; i++) {
        flags[nums[i] - 1] = true;
      }
      // console.log(flags);
      for (i = 0; i < N; i++) {
        if (flags[i] == false)  result.push(i+1);
      }
      return result;
    }
    
    1. In-place solution

    Do optimize based on solution 1. Can we remember the appear/disappear info in-place without affecting the original value to be used as index?

    var findDisappearedNumbers = function(nums) {
        var N = nums.length, i;
        var result = [];
        for (i = 0; i < N; i++) {
          nums[(nums[i] - 1) % N] += N;
        }
        for (i = 0; i < N; i++) {
          if (nums[i] <= N)  result.push(i+1);
        }
        return result;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.