Time Limit Exceeded with Brute Force in LeetCode

Asked 2 years ago, Updated 2 years ago, 46 views

I started LeetCode.

As soon as possible, there was an error in Twosum, so please let me know.
First, I wrote the following code in Brute Force.

class Solution (object):
    defaulttwoSum(self, nums, target):
        """
        :type nums:List [int]
        —type target:int
        :rtype:List [int]
        """
        for i in range (len(nums)) :
            for jin range(1,len(nums)):
                if(i==j):
                    continue
                elif(nums[j]==target-nums[i]):
                    return i,j

When I tried to run it above, I got a Time Limit Exceeded error.
At first glance, it looks fine, but what's the problem?

Please let me know.

python algorithm

2022-09-30 15:36

1 Answers

If I were to modify the code to a minimum, I think it would be as follows.The part in question is the part where the inner for turns the loop from the beginning of the list every time.Change range(1,len(nums)) to range(i+1,len(nums)) because the inside can handle all combinations by processing the following elements of i:Next, correct the inside of the loop and complete.

class Solution (object):
    defaulttwoSum(self, nums, target):
        """
        :type nums:List [int]
        —type target:int
        :rtype:List [int]
        """
        for i in range (len(nums)) :
            for jin range (i+1,len(nums)) :
                if(nums[j]==target-nums[i]):
                    return i,j


2022-09-30 15:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.