In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.