天天看點

LeetCode程式設計練習 - Set Mismatch學習心得

題目:

    The set

S

originally contains numbers from 1 to

n

. But unfortunately, due to the data error, one of the numbers in the set got duplicated toanother number in the set, which results in repetition of one number and loss of another number.

    Given an array

nums

representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

    Example 1:

       Input: nums = [1,2,2,4]

       Output: [2,3]

    Note:

       1、The given array size will in the range [2,10000].

       2、The given array's numbers won't have any order.

    集合S最初包含從1到n的數字,但由于資料錯誤,集合中的一個數字被指派到集合中的另一個數字,導緻重複一個數字和另一個數字的丢失。給定一個數組nums,表示該錯誤之後的資料狀态。先發現數字兩次,然後找到丢失的數字,以數組的形式傳回他們。

思路:

    先發現數字兩次,然後找到丢失的數字,也就是說有最終輸入兩個變量并以數組的形式輸出,初始化兩個變量為0。由于資料丢失時,一個數字被指派到了另一個數字,判斷兩個數字是否相同,若相同則是發生了資料丢失錯誤,然後判斷是否發現數字兩次以及是否丢失數字。

LeetCode程式設計練習 - Set Mismatch學習心得
LeetCode程式設計練習 - Set Mismatch學習心得

    運作結果不符,檢視解決方案,與方案的思路相同,但對于書寫上還是有些差異。

LeetCode程式設計練習 - Set Mismatch學習心得
LeetCode程式設計練習 - Set Mismatch學習心得