給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,并回傳他們的陣列下標,
你可以假設每種輸入只會對應一個答案,但是,陣列中同一個元素不能使用兩遍,
示例:
給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以回傳 [0, 1]
解題思路
直接使用暴力方法,首先找到其中的一個數字,然后在這個數字之后找是否有加起來等于target的數字,沒啥難度:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ i = 0 # 這里用了兩個回圈,最好只能使用一個回圈 while i < len(nums): j = i + 1 while j < len(nums): if nums[i] + nums[j] == target: return i, j j += 1 i += 1 return None
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/643.html
標籤:其他
