[] Array-medium 442. Find All Duplicates in an Array array elements appear twice found.

1. The title site

https://leetcode.com/problems/find-all-duplicates-in-an-array/

2. Title Description

Here Insert Picture Description

3. subject to the effect

Find the array elements appear twice.

4. Problem-solving ideas

  • Because the range of elements that Italy said value of the array is: 1 ≤ a [i] ≤ n (n = size of array) ,. So, we will be an array of values ​​corresponding to the new array element index, appears once, the value +1,
  • Analyzing the final element values ​​of the new array, if more than two, the index will be added to the element of the ret

5. AC Code

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int[] arr = new int[nums.length + 1];
        for(int i = 0; i < nums.length; i++) {
            arr[nums[i]] ++;
        }
        List<Integer> ret = new ArrayList<Integer>();
        for(int i = 1; i <= nums.length; i++) {
            if(arr[i] > 1)
                ret.add(i);
        }
        return  ret;        
    }
}

6. similar topic

. [1] 448 Find All Numbers Disappeared in an Array Topic site: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ problem solving blog: HTTPS: //blog.csdn .net / xiaojie_570 / article / details / 92609678

Guess you like

Origin blog.csdn.net/xiaojie_570/article/details/92611227
Recommended