自己的暴力解法
class Solution { public int firstMissingPositive(int[] nums) { Set<Integer> set = new TreeSet<Integer>(); for(int num: nums){ set.add(num); } System.out.println(set); int i = 1; while(i < nums.length + 1){ if(!set.contains(i)){ return i; } i++; } return i; } }
現在可以開始寫算法了。
檢查 1 是否存在於數組中。如果沒有,則已經完成,1 即為答案。
如果 nums = [1],答案即為 2 。
將負數,零,和大於 n 的數替換為 1 。
遍歷數組。當讀到數字 a 時,替換第 a 個元素的符號。
注意重復元素:只能改變一次符號。由於沒有下標 n ,使用下標 0 的元素保存是否存在數字 n。
再次遍歷數組。返回第一個正數元素的下標。
如果 nums[0] > 0,則返回 n 。
如果之前的步驟中沒有發現 nums 中有正數元素,則返回n + 1。
class Solution { public int firstMissingPositive(int[] nums) { int n = nums.length; // 基本情況 int contains = 0; for (int i = 0; i < n; i++) if (nums[i] == 1) { contains++; break; } if (contains == 0) return 1; // nums = [1] if (n == 1) return 2; // 用 1 替換負數,0, // 和大於 n 的數 // 在轉換以后,nums 只會包含 // 正數 for (int i = 0; i < n; i++) if ((nums[i] <= 0) || (nums[i] > n)) nums[i] = 1; // 使用索引和數字符號作為檢查器 // 例如,如果 nums[1] 是負數表示在數組中出現了數字 `1` // 如果 nums[2] 是正數 表示數字 2 沒有出現 for (int i = 0; i < n; i++) { int a = Math.abs(nums[i]); // 如果發現了一個數字 a - 改變第 a 個元素的符號 // 注意重復元素只需操作一次 if (a == n) nums[0] = - Math.abs(nums[0]); else nums[a] = - Math.abs(nums[a]); } // 現在第一個正數的下標 // 就是第一個缺失的數 for (int i = 1; i < n; i++) { if (nums[i] > 0) return i; } if (nums[0] > 0) return n; return n + 1; } }