LeetCode Two Sum

本文介绍了一种解决两数之和问题的有效算法。给定一个整数数组及目标值,该算法能找出两个数相加等于目标值的索引。通过定义结构体保存数值及其原始索引并进行排序,利用首尾指针逼近的方法找到答案,避免了传统O(N^2)的时间复杂度。

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


注:时间复杂度为O(N*N)的通过不了,所以采用排序,然后首尾逼近,时间复杂度就是排序的O(N*logN),因为排序后数据标号变了,所以定义了一个结构体保存数据及其下标。


struct iNode {
	int num;
	int index;
};

bool cmp(const iNode &a, const iNode &b)
{
	return a.num < b.num;
}

class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target) {
		vector<int> result;
		vector<iNode> ivec;
		for (int i = 0; i < numbers.size(); i++) {
			iNode node;
			node.num = numbers[i];
			node.index = i;
			ivec.push_back(node);
		}

		sort(ivec.begin(), ivec.end(), cmp);

		int i = 0, j = ivec.size() - 1, sum = 0;
		while (i != j) {
			sum = ivec[i].num + ivec[j].num;
			if (sum == target) {
				if (ivec[i].index < ivec[j].index) {
					result.push_back(ivec[i].index + 1);
					result.push_back(ivec[j].index + 1);
				} 
				else {
					result.push_back(ivec[j].index + 1);
					result.push_back(ivec[i].index + 1);
				}
				break;
			}
			else if (sum > target)
				j--;
			else
				i++;
		}
		return result;
	}
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值