How to solve the problem of the Sum of two numbers by LeetCode
Editor to share with you LeetCode how to solve the problem of the sum of two numbers, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
one
Topic description
Given an ordered array that has been arranged in ascending order, find two numbers so that the sum of them is equal to the target number, and meet two requirements: 1, output the subscript values of two numbers in order, the subscript value starts from 1; 2, assume that each input only corresponds to a unique answer, can not reuse the same element. If the input array is [2Power6, 7], and the target value is 8, then [1] is returned, and [2] is not the correct answer.
two
two
Solve a problem
Idea 1: hash table
It is consistent with the idea 2 in LeetCode exercise DAY 8: the sum of two numbers, except that you should put the subscript + 1 when you output, otherwise the subscript starts from 0.
Class Solution: def twoSum (self, numbers: List [int], target: int)-> List [int]: h_map = {} for iMart item in enumerate (numbers): if target-item in h_map: return [h _ map [target-item] + 1 meme 1] h _ map [item] = I
Idea 2: double pointers
Because the array is arranged in ascending order, you can set two pointers to each end of the array, that is, the minimum and maximum values. Calculates the sum of the pointer to the number, if greater than target, the large number pointer minus 1, if less than target, the small number pointer plus 1, and if exactly equal, the output.
Class Solution: def twoSum (self, numbers: List [int], target: int)-> List [int]: iTun0 j=len (numbers)-1 while I