Advertisement
1988coder

268. Missing Number

Jan 28th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.55 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/missing-number/
  2.  
  3. /**
  4.  * Sum all the numbers and subtract the sum from n * (n+1) / 2
  5.  *
  6.  * Time Complexity: O(N)
  7.  *
  8.  * Space Complexity: O(1)
  9.  *
  10.  * N = Length of the input array.
  11.  */
  12. class Solution {
  13.     public int missingNumber(int[] nums) {
  14.         if (nums == null || nums.length == 0) {
  15.             return -1;
  16.         }
  17.  
  18.         int sum = 0;
  19.         int len = nums.length;
  20.         for (int num : nums) {
  21.             sum += num;
  22.         }
  23.  
  24.         return len * (len + 1) / 2 - sum;
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement