Java Solution with Algorithm and step by step explanation


  • 0
    G

    public class Solution {

        /**
         * Algorithm:
         * Step1: create a new arrayList (list) to store the missing elements to be returned and an integer 'length' to store the length of the 'nums' array.
         * Step2: Iterate over the array 'for(i-->[0,length); i++) {Step2, Step3, Step 4}' and create 'index' and initialize 'index=Math.abs(nums[i]) - 1' 'i' is the counter of the current iteration.
         * Step3: Check the value at index 'index' of nums array 'nums[index]'  and if nums[index]>0 goto :Step4
         * Step4: Negate the value at nums[index] (multiple by '-1')
         * Step5: Iterate over the array nums again 'for(i-->[0,length); i++) {Step5, Step6, Step7}'
         * Step6: if nums[i]>0 goto :Step7
         * Step7: Add 'i+1' to 'list'
         * Step8: return 'list'
         * @param nums
         * @return list
         */
        public List<Integer> findDisappearedNumbers(int[] nums) {
            List<Integer> list = new ArrayList<Integer>(); int length = nums.length; //Step1
            for(int i=0; i<length; i++){ //Step2
                int index = Math.abs(nums[i]) - 1; //Step3
                if(nums[index]>0){
                    nums[index] *= -1; //Step4
                }
            }
            
            for(int i=0; i<length; i++){ //Step5
                if(nums[i]>0){ //Step6
                    list.add(i+1); //step7
                }
            }
            return list; //Step8
        }
    
    }```

Log in to reply
 

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