LeetCode167 Two Sum II - Input array is sorted-python(easy)

topic source

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51249/Python-different-solutions-(two-pointer-dictionary-binary-search).

topic analysis

  Given an integer array sorted in ascending order, find two numbers in it, add them to the target value, and finally return the indices of the two numbers. The first index returned needs to be less than the second index, and the index is calculated from 1. Note that there is only one set of solutions for each case, and you cannot use the same elements twice.

  The first idea of ​​​​this topic is to traverse, because it has been sorted, then the two values ​​before and after are added, and the size is compared with the target value, and the corresponding adjustment is made. It should always be noted here that the "pointer" at the beginning cannot exceed the "pointer" at the end, so the traversal process requires a while instead of a for loop.

  The code implemented at this time is:

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        i=0
        j=len(numbers)-1
        while(i<j):
            if(numbers[i]+numbers[j]<target):
                i+=1
            elif(numbers[i]+numbers[j]>target):
                j-=1
            else:
                return [i+1,j+1]

 The second idea uses a dictionary and uses the enumerate() built-in function in the dictionary. This function was also covered before. For an iterable/traversable object (such as a list, a string), enumerate will It consists of an index sequence, which can be used to obtain the index and value at the same time, enumerate is mostly used to get the count in the for loop. Because here we need to compare the value first, and then get its index, so this idea can be considered. Its code is as follows:

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        Dec={}
        for i,number in enumerate(numbers):
            if((target-number) in dic):
                return [dic[target-number]+1,i+1]
            dic[number]=i

 It should be noted that when the elements in the list are put into the dictionary, the value is used as the subscript, and the subscript is used as the value, which has a certain meaning when doing so. If it is reversed, even if you get the corresponding value, you can't know what its subscript is, so you must pay attention here.

  Another idea is binary search, which is mainly used in sorted arrays. The general idea is: first, compare the given value key with the key code (key) of the element in the middle position of the dictionary. If they are equal, the retrieval is successful; otherwise, if the key is small, continue the binary search in the first half of the dictionary. ; If the key is large, continue the binary search in the second half of the dictionary. In this way, after one comparison, the search range is reduced by half, and the process continues until the search succeeds or fails. The even number takes any of the middle 2 as the middle element. Dichotomous retrieval is a highly efficient retrieval method that requires dictionaries to be sorted by key in the sequence table. But here is that we are comparing the sum of the two to the target instead of a single element, so it's a bit complicated. Others' code is as follows:

def twoSum(self, numbers, target):
    for i in xrange(len(numbers)):
        l, r = i+1, len(numbers)-1
        tmp = target - numbers[i]
        while l <= r:
            mid = l + (r-l)//2
            if numbers[mid] == tmp:
                return [i+1, mid+1]
            elif numbers[mid] < tmp:
                l = mid+1
            else:
                r = mid-1

Note that here it is not compared with the target, but it is converted into a comparison with one of the elements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324882591&siteId=291194637