image.png

解题思路

image.png

  1. class Solution {
  2. public List<Integer> findDisappearedNumbers(int[] nums) {
  3. // Iterate over each of the elements in the original array
  4. for (int i = 0; i < nums.length; i++) {
  5. // Treat the value as the new index
  6. int newIndex = Math.abs(nums[i]) - 1;
  7. // Check the magnitude of value at this new index
  8. // If the magnitude is positive, make it negative
  9. // thus indicating that the number nums[i] has
  10. // appeared or has been visited.
  11. if (nums[newIndex] > 0) {
  12. nums[newIndex] *= -1;
  13. }
  14. }
  15. // Response array that would contain the missing numbers
  16. List<Integer> result = new LinkedList<Integer>();
  17. // Iterate over the numbers from 1 to N and add all those
  18. // that have positive magnitude in the array
  19. for (int i = 1; i <= nums.length; i++) {
  20. if (nums[i - 1] > 0) {
  21. result.add(i);
  22. }
  23. }
  24. return result;
  25. }
  26. }