LeetCode Add Two Numbers

问题描述:https://leetcode.com/problems/two-sum/

<pre name="code" class="cpp"><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given an array of integers, find two numbers such that they add up to a specific target number.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">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.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">You may assume that each input would have exactly one solution.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-size: 14px; line-height: 30px; font-family: monospace;"><span style="box-sizing: border-box; font-weight: 700;">Input:</span> numbers={2, 7, 11, 15}, target=9<br style="box-sizing: border-box;" /><span style="box-sizing: border-box; font-weight: 700;">Output:</span> index1=1, index2=2</p>

 

问题关键在于,对vector进行排序,排序之后,index1和index2指针一个从前一个从后开始向中间扫描。刚开始的时候,想着直接使用vector自带的排序,但是怕LeetCode没有包含algorithm头文件,所以使用选择排序,但是超时了。最后,到网上一看,发现原来LeetCode包含了algorithm头文件的。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> tempv(nums);
	sort(tempv.begin(), tempv.end());
	int index1 = 0, index2 = tempv.size()-1;
	while (tempv[index1]+tempv[index2]!=target)
	{
		if (tempv[index1] + tempv[index2] < target)
			index1++;
		else
			index2--;
	}
	int start = tempv[index1], end = tempv[index2];
	int i = 0;
	while (nums[i] != start)
	{
		i++;
	}
	vector<int> rs;
	start=i+1;
	i = nums.size() - 1;
	while (nums[i] != end)
		i--;
	end=i+1;
	rs.push_back(start<end?start:end);
	rs.push_back(start<end?end:start);
	return rs;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值