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()
, ArrayList
the 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 ArrayList
the 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 HashSet
its add()
method will automatically de-emphasis, it is a call map
of the put
method, 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 List
the contains()
method, its efficiency is very low, you can consider using it Set
to achieve.