twoSum Algorithm : How to improve this?

前端 未结 22 2119
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  天涯浪人
    2021-02-06 02:13

    1. Sort the list in non-decreasing order. It takes O(nlogn) time complexity.
    2. Find the two numbers, which can be done in O(n) time.
    3. Find the two indices of the two numbers, which can be done in O(n) time.

    Overall complexity is O(nlogn).

    Implementation in python:

    class Solution:
      def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        p = nums[:]
        p.sort() #sorting in -> O(nlogn)
        r = len(nums)-1
        l =0 
    
        #find the indices -> O(n)
        for i in range(len(nums)):
          if(p[l] + p[r]target): 
            r -=1
          else :
            first_num = p[l]
            second_num = p[r]
    
        #find the indices of the numbers -> O(n)
        for i in range(len(nums)):
          if(nums[i]==first_num):
            first_index = i
          elif (nums[i]==second_num):
            second_index = i
        return [first_index,second_index]
    

提交回复
热议问题