98%. Without using java.Math.


  • 0
    L

    Idea:
    first loop: swap the element to the corresponding index.
    second loop: check if there is an element is not in the right position, add it to result list.

    public List<Integer> findDuplicates(int[] nums) {
            if (nums == null || nums.length == 0) {
                return new ArrayList<>();
                // throw new IllegalArgumentException("Invalid Input!");
            }
            List<Integer> result = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != nums[nums[i] - 1]) {
                    swap(nums, i, nums[i] - 1);
                    i--;
                }
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i + 1) {
                    result.add(nums[i]);
                }
            }
            return result;
        }
        private void swap(int[] nums, int index1, int index2) {
            int temp = nums[index1];
            nums[index1] = nums[index2];
            nums[index2] = temp;
        }
    

Log in to reply
 

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