Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].分析解答
給定了唯一解限定、vector配合class的測試,輸入省去了數(shù)據(jù)輸入輸出的麻煩。確實是比較簡單的一道題目,問題僅僅在于效率如何提高上面。下面列舉幾種可能的算法分析和測試結(jié)果。算法1:暴力搜索class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int N = nums.size(); for (int i = 0; i < N-1; i++) for (int j = i+1; j < N; j++) { if (nums[i] + nums[j] == target) { vector <int> result; result.push_back(i); result.push_back(j); return(result); } } }};算法的想法及其簡單,就是一輪冒泡對比,如果相加得到可行的解,則立刻返回結(jié)果結(jié)束程序。Result:2017年2月,LeetCode平臺,AC,190ms,優(yōu)于30%的算法。算法2:哈希法(簡單查表)
新聞熱點
疑難解答