I have this for loop:
public void method(int[] arr) {
Set set = new HashSet();
for(int i = 0; i < arr.length; i++){
set.add(arr[i]);
}
}
is this method in O(n)?
I have this for loop:
public void method(int[] arr) {
Set set = new HashSet();
for(int i = 0; i < arr.length; i++){
set.add(arr[i]);
}
}
is this method in O(n)?
If you use a HashSet, yes.
HashSet
has O(1)
and you multiply it with O(n)
by using a for-loop. Thus, the whole construct has O(n)
.
HashSet
has a near-linear insertion performance, so yes: n such operations would be O(n).
Note that I would do this instead, which achieves exactly the same result as what all your code does:
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
You shoukd type your Set too, as above.