LeetCode 1:兩數之和
阿新 • • 發佈:2018-11-11
題目
給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
示例
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
C++版本解答:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; int n=nums.size(); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(nums[i]+nums[j]==target){ result.push_back(i); result.push_back(j); break; } } if(!result.empty()){ break; } } return result; } };
Python版本解答:
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i]+nums[j] == target: return '[%s,%s]'%(i,j) return None