1. Two Sum
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.
问题描述:
给了一个数组和一个目标数target,要求找出数组中的两个数加起来恰好是target,然后返回这两个数的位置。
题目中给出了条件是有且仅有一个可行解。
思路:
刚开始不知道怎么写,就干脆利落的写了一个特别质朴的算法。考虑数组中所有的二元对,一共是有n*(n-1)/2个。枚举所有的可能,并且在找到时退出,不然就继续找。显然这样可以正确的得到结果,显然这样会超时QAQ为了聊表寸心我还是贴上这个质朴的O(n^2)的算法吧。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { //a naive version //match all the possible versions vector<int> result; vector<int>::iterator i,j; bool findanswer=false; for (i=nums.begin();i!=nums.end();i++) { if (findanswer) break; for (j=i+1;j!=nums.end();j++) { if (findanswer) break; if ((*i)+(*j)==target) { result.push_back((int)(i-nums.begin())); result.push_back(j-nums.begin()); findanswer=true; } } } return result; } };
质朴而naive的算法当然是超时了啦,