leetcode 1. Two Sum

1.题目描述                                                                                                        

Total Accepted: 171781  Total Submissions: 850971  Difficulty: Medium

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

在数组中找到两个数,使这两个数的和等于目标值。


2.分析                                                                                                               

思路一:

首先想到用map映射来做。map<int,int>中,key记录数组的值,value记录下标。遍历nums数组,在map中找到target-nums[i],如果找到,则返回下标。

class Solution {
public:
   vector<int> twoSum(vector<int>& nums, int target) {
	map<int, int> mp;
	vector<int> ans;
	for (int i = 0; i < nums.size(); i++)
		mp[nums[i]] = i;
	for(int i=0;i<nums.size();i++)
    {
        if(mp.find(target-nums[i])!=mp.end() && i!=mp.find(target-nums[i])->second)
        {
            ans.push_back(i+1);
            ans.push_back((mp.find(target-nums[i])->second)+1);
            break;
        }
    }
    return ans;
}
};
思路二:

用“逼近”的算法。首先新建一个数组存储原数组的值,再将新建的数组排序。用temp表示。然后left从左至右扫描,right从右至左扫描。

我们可以知道,如果temp[left]+temp[right]>target,那么肯定有一个数大了,那么就使right--;

同样,如果temp[left]+temp[right]<target,那么肯定有一个数小了,使left++;

如果相等,则找到了要找的数,但是这里的left和right并不是原数组的下标,所以还得在原数组中再找一遍。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> temp = nums;
    sort(temp.begin(),temp.end());
    int left = 0;
    int right = temp.size()-1;
    while(temp[left]+temp[right] != target)
    {
        if(temp[left]+temp[right] > target)
            right--;
        else
            left++;
    }
    vector<int> array(2,0);
    for(int i=0;i<temp.size();i++)
    {
        if(nums[i] == temp[left] || nums[i] == temp[right])
            if(array[0] == 0)
                array[0] = i+1;
            else
                array[1] = i+1;
    }
    return array;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值