Java solution, beats 94%, easy to understand than abs()


  • 1
    J

    Use modulo operation to retrieve original data and due to the question requirement that all the elements are range from 1 to n inclusive, so after increment "len", the elements that have appeared once will range from len+1 to 2len. Hence the duplicates will range from 2len+1 to 3len in the same way. :) Hope it helps.

        public List<Integer> findDuplicates(int[] nums) {
            int len = nums.length;
            for(int i = 0 ; i < len ; i++){
                nums[(nums[i]-1)%len] +=len;
            }
            List<Integer> res = new ArrayList<>();
            for(int i = 0 ; i < nums.length ; i++){
                if(nums[i]>2*len){
                    res.add(i+1);
                }
            }
            return res;
        }
    }

  • 0
    L

    I don't understand your algorithm, but I think it's a very good method. Can you explain in detail why you want to do this? What did you think of that? Sorry for my poor English.


Log in to reply
 

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