Two sum(在数组中找两个数,使其和为指定值)

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

    Hide Tags
      Array Hash Table
    Solutions:
    1)最直接的O(N^2)的算法,再leetCode上超时。
    2)先将数组排序,再从两端向中间查找,因为有可能有相等的元素,所以找第二个数的位置时要从高端开始。
    class Solution {
    public:
    	vector<int> twoSum(vector<int>& nums, int target) {
    		vector<int> v=nums;
    		sort(v.begin(), v.end());
    		int l=0, r=v.size()-1;
    		while(l<r){
    			if(v[l]+v[r]>target) {
    				--r;
    			}
    			else if(v[l]+v[r]<target) {
    				++l;
    			}
    			else{
    				break;
    			}
    		}
    		int i=0;
    		for(i=0; i<nums.size(); ++i) {
    			if(nums[i] == v[l]) {
    				l=i+1;
    				break;
    			}
    		}
    		for(i=nums.size()-1; i>=0; --i) {
    			if(nums[i] == v[r]) {
    				r=i+1;
    				break;
    			}
    		}
    		vector<int> ret;
    		if(l>r){
    			swap(l, r);
    		}
    		ret.push_back(l);
    		ret.push_back(r);
    		return ret;
    	}
    };

    3)用一个map<int, int>存储已经遍历过的数,键为数,值为位置(从1开始)。遍历到某数x,若target-x已经被遍历过,则此2数即为所求。
    但其时间反而比上面的要长。
    class Solution{
    public:
    	vector<int> twoSum(vector<int> &nums, int target) {
    		map<int, int> m;
    		int l=0, r=0;
    		for(l=0; l<nums.size(); ++l) {
    			if((r=m[target- nums[l]]) != 0) {			
    				break;
    			}
    			m[nums[l]]=l+1;
    		}
    		l+=1;
    		if(l>r) {
    			swap(l, r);
    		}
    		vector<int> ret;
    		ret.push_back(l);
    		ret.push_back(r);
    		return ret;
    	}
    };







    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值