1 Two Sum

Link: https://oj.leetcode.com/problems/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

要求为给出的数组中,找出两个数字相加为指定的数,已知数组中只有唯一一组相加为给定值的的正确组合,所求是俩个值所在位置(非0开始)

思路:由于答案唯一,每两个数值两两相加可以得到。

1 将数组排序,指向头尾两个数字

2 两个数字相加后,如果大于所给值,需要一个减小的过程,所指尾部位置-1,缩减相加的量;如果小于所给值,头部位置+1,增加所加的量。

3 重复第2步,总能获得相加等于给定值的两个数字,注意求为位置,不是数值。

由于过程需要排序,所以需要复制数组以保存原数组的位置。

由值求原数组位置时,注意如果求出的两个值为相同时,将获得两个相同位置:

[3,4,1,4,9,2,10],求8,排序为[1,2,3,4,4,9,10],从4,4获得4个位置,将取不同的两个位置为答案

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
		vector<int> nums = numbers;  // 拷贝数组以保存原位置

		sort(nums.begin(),nums.end());
		int beg = 0, end = nums.size()-1;
		vector<int> re;
		for(;beg<end;)
		{	if(nums[beg]+nums[end]> target) {
				--end;
			}
			else if(nums[beg]+nums[end]< target){
				++beg;
			}
			else
			{	for(unsigned long i=0; i<numbers.size();i++){  // 将位置入栈,如果[beg]==[end]时,获得4个位置
					if(numbers[i]==nums[beg]) 
						re.push_back(i+1);
					if(numbers[i]==nums[end]) 
						re.push_back(i+1);
				}
				if(re.size()>2) {
					re[1]=re[2];  // 4个位置时,调换相同值
				}
				return re;
			}
		}
		return re;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值