LeetCode:268. Missing Number(遺失的數字)
阿新 • • 發佈:2018-11-23
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
這個題目很簡單,應該拿到題目就會的,但是有最優解;我先給出了這移動比較直白的思路:
方法1:
public int missingNumber(int[] nums) { int length = nums.length; Set<Integer> set = new HashSet<>(); for (int i = 0; i < length + 1; i++) { set.add(i); } for (int i = 0; i < length; i++) { if (set.contains(nums[i])) { set.remove(nums[i]); } } return (int) set.toArray()[0]; }
這種思路最容易想到,但是效率不高;
時間複雜度:O(n);
空間複雜度:O(n);
方法2:
利用加減的方法,自己沒有考慮到邊界問題,可以注意下邊界問題,但是為了問題解決的方便,我先沒考慮它的值超過Integer.Max_VALUE的解決辦法。直接計算:
public int missingNumber2(int[] nums) { int sum = 0; int n = nums.length; int totalSum = (n + 1) * n / 2; for (int i = 0; i < n; i++) { sum += nums[i]; } return totalSum-sum; }
時間複雜度:O(n)
空間複雜度:O(1)