一、題目名稱java
Missing Number (缺失的數字)數組
二、題目地址code
https://leetcode.com/problems/missing-number排序
三、題目內容leetcode
英文:Given an array containing n distinct numbers taken from 0, 1, 2, ..., n find the one that is missing from the array.開發
中文:給出一個包含了n個不一樣數字的數組,從0開始一直到n,找出缺失的數字。若是數組是連續的則返回n+1。get
例如:給出的數組爲 [0, 1, 3] 則返回2io
四、解題方法1class
第一種方法是對原數組進行排序,而後使用一個計數用的變量按序考察排序後的數組,若是數組的第n位不等於n,則返回n,不然返回數組長度加一。import
一段實現本方法的Java代碼爲:
import java.util.Arrays; /** * 功能說明:LeetCode 268 - Missing Number * 開發人員:Tsybius2014 * 開發時間:2015年8月25日 */ public class Solution { /** * 找出丟掉的數字 * @param nums * @return */ public int missingNumber(int[] nums) { Arrays.sort(nums); int counter; for (counter = 0; counter < nums.length; counter++) { if (counter != nums[counter]) { return counter; } } return counter; } }
五、解題方法2
第二種方法是創建一個新數組,長度爲老數組的長度加一,新數組內的元素順序排列。在老數組中每找到一個數字,都將新數組中對應位置變爲-1,則最後新數組中未被變爲-1的數字即爲所求。
一段實現本方法的Java代碼爲:
/** * 功能說明:LeetCode 268 - Missing Number * 開發人員:Tsybius2014 * 開發時間:2015年8月25日 */ public class Solution { /** * 找出丟掉的數字 * @param nums * @return */ public int missingNumber(int[] nums) { int[] nums2 = new int[nums.length + 1]; for (int i = 0; i < nums2.length; i++) { nums2[i] = i; } for (int i = 0; i < nums.length; i++) { nums2[nums[i]] = -1; } for (int i = 0; i < nums2.length; i++) { if (nums2[i] != -1) { return i; } } return -1; } }
END