Leetcode 1.Two Sum



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的算法当然是超时了啦,





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值