I want to know why my solution like this was time_limmit exceeded!


  • 0
    1
     public boolean containsDuplicate(int[] nums) {
            ArrayList<Integer> arrayList = new ArrayList<>();
            boolean flag = false;
            for (int i = 0; i < nums.length; i++) {
                if (arrayList.contains(nums[i])) {
                    flag = true;
                    break;
                } else {
                    arrayList.add(nums[i]);
                }
            }
            return flag;   
        }
    

  • 0
    R

    ArrayList contains method takes O(n).(searching requires iterating the list)

    So, your algorithm is O(n^2), and there are many O(n) or O(n logn) solutions.

    I recommend you to use HashSet instead of ArrayList


Log in to reply
 

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