Java 8 Stream time O(n), space O(1)


  • 0
    J

    Pretty simple - unfortunately using stream is very slow :(

    public class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length;
            return n*(n+1)/2 - Arrays.stream(nums).sum();
        }
        
    }
    

    Faster solution (1ms), same thing without the stream:

     public int missingNumber(int[] nums) {
            int sum = 0;
            int n = nums.length;
            
            for(int i = 0; i < n; i++)
                sum += nums[i];
            
            return n*(n+1)/2 - sum;
        }
    

Log in to reply
 

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