LeetCode1-TwoSum

题目要求:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Subscribe to see which companies asked this question.


思路:

将target-nums的差保存,并在nums中查找该差值,找到时输出nums所在下标和差所在下标即可,如代码1所示。

查找差值时,可使用二分查找算法,如代码2所示。

代码1如下:

#include<iostream>
#include<vector>
#include<iterator>
using namespace std;

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		char num=0;
		int a;
		int n=3;
		vector<int> res;
		int left = -1, right = -1;
		
		//cout << "输入数组:" << endl;
		//n
		while ((cin.peek() != EOF) && (cin.peek() != '\n'))//次数问题
		{
			cin >> num;
			//cout << num;
			
			if (num =='0'|| num == '1' || num == '2' || num == '3' || num == '4' || 
				num == '5' || num == '6' || num == '7' || num == '8' || num == '9' )
			{
				//cout << num<<",";
				a = num - '0';
				nums.push_back(a);
			}
			//if (cin.get() == '\n') break;
			//n--;
		}
		//cout << "输入和:" << endl;
		cin >> target;
		vector<int> cha;
		for (vector<int>::iterator it=nums.begin();it!=nums.end();it++)
		{
			cha.push_back(target - *it);
		}
		for (vector<int>::iterator it = cha.begin();it != cha.end();it++)
		{
			int i = it - cha.begin();
			for (vector<int>::iterator it1 = nums.begin();it1 != nums.end();it1++)
			{
				int j = it1 - nums.begin();
				if (i!=j&&*it == *it1)
				{
					res.push_back(it-cha.begin());
					res.push_back(it1-nums.begin());
					return res;
				}
			}
		}

		return res;
	}

};

int main()
{
	Solution a;
	vector<int> nums;
	vector<int> res;
	int target=0;
	char s=0;
	//cout << "输入和:" << endl;
	//cin >> target;
	//cin >> s;
	//cout << s<<endl;
	res=a.twoSum(nums,target);
	//nums.push_back(5);
	//nums.push_back(8);
	
	if (res.end() > res.begin())
	{
		cout << "[";
		vector<int>::iterator it;
		for (it = res.begin();it < res.end() - 1;it++)
			cout << *it << ",";
		it = res.end() - 1;
		cout << *it;
		cout << "]" << endl;
	}
	else
		cout << "Can't find!" << endl;
	

	system("pause");
	return 0;
}


代码2如下:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值