Is the time complexity of this code O(n^2)?

2019-08-18 11:23发布

The problem finds two items in the array that add up to target value. It returns an array w/ the index of the correct values.

I think the time complexity is n^2 because the while loop runs through array once so n time. And in the worst case, it has to repeat this n times. So n*n running time.

Even though the number of elements it has to iterate through decreases each time, we drop the constants when calc. time complexity.

Is this analysis correct? Any recommendations for bringing it down to n?

def twoSum(nums, target):

    indx = []
    size = len(nums)

    if (size < 2):
        return indx

    x = 0
    y = size - 1

    while(x < y):

        if( (nums[x] + nums[y]) == target):
            indx[0] = x
            indx[1] = y
            break
        elif ( (y - 1) == x):
            x = x + 1
            y = size - 1
        else:
            y = y -1

    return indx

1条回答
姐就是有狂的资本
2楼-- · 2019-08-18 11:33

You can do O(n), this is a google interview question that they have a video on YouTube for I believe. Or at least they had a very similar problem:

def twoSum(nums, target):
    values = dict()
    for index, n in enumerate(nums):
        if target - n in values:
            return values[target - n], index
        else:
            values[n] = index


print(twoSum([4, 5, 2, 1, 3], 4)) # (3, 4)

- Edit -
Per the comments below, this solution technically still has a worst case of O(n^2) do to hash collisions. For most cases you should get close to O(n) but if you are working with large numbers (negative or positive) you will see an increase in collisions which will result n * log(n) to n^2 time (especially if the test set given to you tries to target hash collisions).

查看更多
登录 后发表回答