Java實現 LeetCode 448 找到全部數組中消失的數字

448. 找到全部數組中消失的數字

給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另外一些只出現一次。java

找到全部在 [1, n] 範圍之間沒有出如今數組中的數字。數組

您能在不使用額外空間且時間複雜度爲O(n)的狀況下完成這個任務嗎? 你能夠假定返回的數組不算在額外空間內。app

示例:ide

輸入:
[4,3,2,7,8,2,3,1]code

輸出:
[5,6]
經過次數29,638提交次數51,956it

class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> results = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[Math.abs(nums[i]) - 1] > 0) { nums[Math.abs(nums[i]) - 1] = - nums[Math.abs(nums[i]) - 1]; } } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { results.add(i + 1); } } return results; } } class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> results = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[Math.abs(nums[i]) - 1] > 0) { nums[Math.abs(nums[i]) - 1] = - nums[Math.abs(nums[i]) - 1]; } } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { results.add(i + 1); } } return results; } }

448. 找到全部數組中消失的數字

給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另外一些只出現一次。io

找到全部在 [1, n] 範圍之間沒有出如今數組中的數字。class

您能在不使用額外空間且時間複雜度爲O(n)的狀況下完成這個任務嗎? 你能夠假定返回的數組不算在額外空間內。List

示例:di

輸入:
[4,3,2,7,8,2,3,1]

輸出:
[5,6]
經過次數29,638提交次數51,956

class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> results = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[Math.abs(nums[i]) - 1] > 0) { nums[Math.abs(nums[i]) - 1] = - nums[Math.abs(nums[i]) - 1]; } } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { results.add(i + 1); } } return results; } } class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> results = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[Math.abs(nums[i]) - 1] > 0) { nums[Math.abs(nums[i]) - 1] = - nums[Math.abs(nums[i]) - 1]; } } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { results.add(i + 1); } } return results; } }
相關文章
相關標籤/搜索