Can someone tell me why I get TLE when I use HashSet to store?


  • 0

    The code is shown below. I think contains method for HashSet is O(1), but why there is a TLE?
    Now I am wondering whether contains method for HashSet is O(1) or not?

    class Solution {
    public int arrayNesting(int[] nums) {
    int max = 0;
    for (int i = 0; i < nums.length; i++) {
    Set<Integer> set = new HashSet<>();
    int item = nums[i];
    while (!set.contains(item) && set.size() <= nums.length) {
    set.add(item);
    item = nums[item];
    }
    max = Math.max(set.size(), max);
    }
    return max;
    }
    }


Log in to reply
 

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