1. 程式人生 > >LeetCode刷題——第一題 (兩數之和)

LeetCode刷題——第一題 (兩數之和)

1.兩數之和

題目描述

給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。

你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。

示例:

給定 nums = [2, 7, 11, 15] ,target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路

  • 順序遍歷陣列, i
    i
    從第一個數開始,找與它相加得到target值的 j j ,而 j j i
    + 1 i+1
    到最後一個數。從而遍歷整個陣列。
  • 缺點:陣列中若存在值就是target的情況時處理不能;效率太低,僅僅擊敗了14%滴小盆友。

程式碼實現

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
for i in range(len(nums)-1): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: return [i,j]

可能出現的問題

  • IndentationError: unindent does not match any outer indentation level
    這說明,縮進出了問題,試了好多次,重新自己打把,莫名其妙