leetcode演算法:Two Sum II - Input array is sorted

來源:互聯網
上載者:User

標籤:target   add   color   list   sed   cti   base   art   思路   

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

 

這道題描述的是: 給我們一個 非降序的數組 和 一個 目標值要我們在 數組中 找到兩個數的 索引位置,  這兩個數滿足 相加的值是目標值 並且 案例保證 一定有唯一的答案。不會出現多個和無解要求 數組中每個元素只能使用一次! 我的思路:因為答案是唯一的,不會出現多個  也不會沒有 所以省去很多步驟。我從start(初始為0) 和 last(最後一個位置) 向中間找如果 相加大於目標  last左移如果 相加小於目標 start右移 相等的時候 返回 start 和 end  我的python代碼:
 1 class Solution(object): 2     def twoSum(self, numbers, target): 3         """ 4         :type numbers: List[int] 5         :type target: int 6         :rtype: List[int] 7         """ 8         start, end = 0 , len(numbers) - 1 9         while True:10             if numbers[start] + numbers[end] > target :11                 end -= 112             elif numbers[start] + numbers[end] < target :13                 start += 114             else :15                 break16         return (start+1 , end+1 )17 18 19 if __name__ == ‘__main__‘:20     s = Solution()21     res = s.twoSum([2,3,4],6)22     print(res)

 

   

leetcode演算法:Two Sum II - Input array is sorted

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.