leetcode 1:Two Sum

来源:互联网 发布:ba无标度网络模型 编辑:程序博客网 时间:2024/06/05 21:13

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解法1:(时间复杂度为O(N^2))

(强搜法)直接以第i个数(i从0到nums.size()-1)作为构成和为target的第一个数,然后在剩余的数组中找target-nums[i]。若为真,则将找到的两个数存入rlt数组,并且输出;否则继续找。最后若没有找到,输出0。

代码1:
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
     vector<int>  rlt;
     vector<int>::iterator iter;
int i = 0; for (i = 0;i < nums.size() - 1;i++){ iter = find(nums.begin()+i+1, nums.end(), target - nums.at(i)); if (iter!= nums.end()) { rlt.push_back(i); rlt.push_back(iter-nums.begin()); break; } } return rlt;   
    }
};

结果:AC,but时间579ms,哭死。于是寻求改进的方法。

听说用数组实现比较快,试下:

代码2:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>  rlt;
    int i = 0, j = 0,n = nums.size();
    for (i = 0;i < n;i++){
    for(j = i+1;j<n;j++)
    if (nums[j]== target-nums[i]){
    rlt.push_back(i);
    rlt.push_back(j);
    return rlt;
    }
    }
    return rlt;   
    }
};

结果:AC,but时间依然516ms居高不下,嗯,过一段时间再来优化

 





0 0