1. 程式人生 > 其它 >【LeetCode】268. Missing Number 丟失的數字(Easy)(JAVA)

【LeetCode】268. Missing Number 丟失的數字(Easy)(JAVA)

技術標籤:Leetcode演算法leetcodejava資料結構動態規劃

【LeetCode】268. Missing Number 丟失的數字(Easy)(JAVA)

題目地址: https://leetcode.com/problems/missing-number/

題目描述:

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

Example 4:

Input: nums = [0]
Output: 1
Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums.

Constraints:

  • n == nums.length
  • 1 <= n <= 10^4
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

題目大意

給定一個包含 [0, n]中n個數的陣列 nums ,找出 [0, n] 這個範圍內沒有出現在陣列中的那個數。

進階:

  • 你能否實現線性時間複雜度、僅使用額外常數空間的演算法解決此問題?

解題方法

  1. 題目要求空間複雜度 O(1),時間複雜度是 O(n),就不能用額外的陣列(用額外的陣列的話,直接建立一個 n 長度的陣列,給出現過的位置置為 true,最後哪個位置為 false 就是丟失的數)
  2. 從頭往後遍歷,如果 nums[i] = i 也就是相應的數字在對應的位置,那就繼續
  3. 如果不在對應位置, next = nums[i], 就把 nums[next] 填上 next 也就是對應的位置,然後再把 nums[next] 先前的數字放在對應位置,不斷迴圈(如: [0,2,4,5,3], nums[2] = 2, nums[4] = 4, nums[3] = 3, 因為 5 超出範圍了,所以停止了迴圈)
class Solution {
    public int missingNumber(int[] nums) {
        if (nums.length <= 0) return 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == i) continue;
            int next = nums[i];
            while (next < nums.length && next != nums[next]) {
                int temp = nums[next];
                nums[next] = next;
                next = temp;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i) return i;
        }
        return nums.length;
    }
}

執行耗時:1 ms,擊敗了54.93% 的Java使用者
記憶體消耗:39 MB,擊敗了65.17% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新