LeetCode 解題練習:Two Sum (Easy)
題目原文描述 https://leetcode.com/problems/two-sum/description/ 中文描述 指定一個整數陣列 nums 以及一個整數 target,找出在陣列中的兩個整數總合為 target 之索引位置。可以假設每組測試資料剛好只有一組不重複的答案,且一個陣列元素只會使用一次。 範例一: 輸入 nums = [1, 3, 5, 9], target = 8 輸出 [1, 2] 因為 nums[1] + nums[2] = 3 + 5 = 8 範例二: 輸入 nums = [1, 3, 5, 2, 9], target = 10 輸出 [0, 4] 因為 nums[0] + nums[4] = 1 + 9 = 10 解法一:暴力法 Brute Force 使用迴圈找出陣列中任兩個元素 nums[i] + nums[j] 的總和是否等於 target 。 Python Code class Solution : def twoSum ( self , nums : List[ int ], target : int ) -> List[ int ]: eleLen = len (nums) for i in range (eleLen): for j in range (i + 1 , eleLen): if nums[i] + nums[j] == target: return [i, j] C++ Code class Solution { public: vector < int > twoSum ( vector < int > & nums , int targ...