My O(1) space solution without Math.abs() function or % operation


  • 0

    Traverse every element in the array and swap the wrong placed number to the right place and set it to -1(or any number not in the range). Then traverse again, add the none -1 element to the list.

    public class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            List<Integer> list = new ArrayList<>();
            if (nums == null || nums.length == 0){
                return list;
            }
            int i = 0;
            while(i < nums.length){
                if (nums[i] != -1 && nums[i] != i+1 && nums[nums[i] - 1] != -1){
                    int tmp = nums[i] - 1;
                    nums[i] = nums[tmp];
                    nums[tmp] = -1;
                }else{
                    if (nums[i] == i+1){
                        nums[i] = -1;
                    }
                    i++;
                }
            }
            for(i = 0; i < nums.length; i++){
                if(nums[i] != -1){
                    list.add(i + 1);
                }
            }
            return list;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.