[Sword refers to offer.03] Repeated numbers in the array

topic:

Find the repeated numbers in the array.

All numbers in an array nums of length n are in the range of 0~n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, nor do I know how many times each number is repeated. Please find any duplicate number in the array.

Example: Input: [2, 3, 1, 0, 2, 5, 3] Output: 2 or 3

class Solution {
    public int findRepeatNumber(int[] nums) {
HashSet<Integer> l =new HashSet<>();
        for(int i:nums){
if(!l.contains(i))
l.add(i);
else
    return i;}
        return 0;
    }
}

Analysis: Using ArrayList will time out because ArrayList is a sequential structure and allows data repetition, while HashSet is an unordered structure and does not allow duplicate data. The details are as follows:

ArrayList:

Because there are repeated elements in the data contains(), ArrayListthe contains()method is used . However, the method will call its indexOf()method. Inside the indexOf()method, there is a for loop. Therefore, the time complexity of ArrayListthe contains()method isO(n)。

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }    

HashSet:

For HashSetits add()method will automatically de-emphasis, it is a call mapof the putmethod, the time complexity is O(1).

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

in conclusion:

Therefore, when there is a large amount of data, do not use Listthe contains()method, its efficiency is very low, you can consider using it Setto achieve.

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/113824397