Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
class Solution { public: vector沒錯,想嘛,堂堂LeetCode中等難度的題目,就這樣可以AC的話豈不是。。。於是,我就得到了這樣的回應: Status:twoSum(vector &numbers , int target) { vector index; for(int i=0 ; i!=numbers.size(); i++) { for(int j=numbers.size()-1 ; j>i; j--) if((numbers[i]+numbers[j]) == target) { index.push_back(i+1); index.push_back(j+1); break; } }//for return index; }//twoSum };
class Solution { public: vectortwoSum(vector &numbers , int target) { vector index; map hashMap; for(unsigned int i=0 ; i 這樣,算法復雜度就降到了O(n),順利AC了我的第一個LeetCode題目。 看來,自己還是水到家了,還需要繼續努力! 測試main函數:
為了方便程序測試,這兒也提供main函數的代碼,供於參考:int main() { Solution s; int arr[3] = {3,2,4}; int target = 6; vectornumbers(arr , arr+3); vector index; index = s.twoSum(numbers , target); cout<<"index1="<