LeetCode Two Sum

问题描述:https://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

首先,根据题目给出的例子,大家一般都会想到利用两个头尾指针的方式进行运算。方法在于index1指向vector[0],index2指向vector[size()-1],然后计算Index1和index2所指的数值之和,如果和大于target,证明需要讲index2--,反之需要将index1++,如果想等,则直接返回index1和index2即可。

但是测试数据却不是完全有序的,刚开始我以为LeetCode并没有包含algorithm头文件,所以使用选择插入排序进行vector排序,时间复杂度为O(n2),提交之后超时了。后来才知道,原来LeetCode已经包含了algorithm头文件,所以该用sort函数完成vector的排序,时间复杂度为O(nlogn)。

由于题目要求输出的是原先列的索引,所以我们需要复制一个新的vector,对新的vector进行排序,在新的vector寻找和等于target的两个元素,然后在原先的vector中查找这两个元素,代码如下:

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、付费专栏及课程。

余额充值