啦啦啦,欢迎开启LeetCode刷题的旅程。
这将是一段漫长而又艰辛的旅程,这是一条攀登珠穆朗玛的皑皑雪山路,这是通向One Piece宝藏的伟大航路,这是无比残酷的修罗场。
但请不要害怕,我们一起努力,必将一路披荆斩棘,将各位带到成功的彼岸,不过一定要牢记的是,不要下船,不要中途放弃,要坚持,要自我修炼,不断成长!那么,起航吧~
这道Two Sum的题目作为LeetCode的开篇之题,乃是经典中的经典,正所谓‘平生不识TwoSum,刷尽LeetCode也枉然’。
就像英语单词书的第一个单词总是Abandon一样,很多没有毅力坚持的人就只能记住这一个单词,所以通常情况下单词书就前几页有翻动的痕迹,后面都是崭新如初,道理不需多讲,鸡汤不必多灌,明白的人自然明白。
废话不多说,开始进入答题模式——
两数之和 Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
1 2 3 4 |
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[<strong>0</strong>] + nums[<strong>1</strong>] = 2 + 7 = 9 所以返回 [<strong>0, 1</strong>] |
解答
1 2 3 4 5 6 7 8 9 10 11 12 |
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): if target - nums[i] in nums: for j in range(len(nums)): if i != j and target - nums[i] == nums[j]: return [i, j] |
输出结果
我的输入
1 2 |
[2,7,11,15] 9 |
我的答案
1 |
[0,1] |