LeeCode编程训练日记一:Two Sum

通过Leecode训练编程,每天只做一个题目,重在训练编程思想

Practice Day 1: 2017/06/25 

参考:http://blog.csdn.net/murdock_c/article/details/49851547

test 1:

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].

解答:

1、暴力计算(不推荐,时间复杂度太高)

#include<iostream>
using namespace std;

int main() {
     int arr[4] = {2,7,11,15}
     int target;
     int a,b; 
     cin >> target;
     int length = sizeof(arr)/sizeof(arr[0]);
     for(int i = 0; i < length; i++){
	for(int j = i+1; j< length; j++) {
		if(arr[i] + arr[j] == target)
		{
			a = i;
			b = j;
			break;
     		}
	  }
    cout << arr[a] << " & " << arr[b] << endl;
    return 0; 
}

2、c++ map的方法来做,时间复杂度因为map查找速度快的原因而大大下降

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

class Solution {
public:
      vector<int> twosome(vector<int> numbers, int target) {
      int i, sum;
      vector<int> results;
      map<int, int> hmap;
      for(int i=0; i < numbers.size(); i++)
	{
	   if(!hmap(numbers[i])){
		map.insert(pair<int,int>(numbers[i], i));
	   }
           if(map.count(target - numbers[i]))
	{
	   int n = hmap[target - numbers[i]];
	   if(n < i)
	{
	   results.push_back(n);
	   results.push_back(i);
	   return results;
	}
     }
     return results;
}
};

int main() {
	vector<int> numbers = {2,7,11,15};
	vector<int> res;
	int target;
	cin >> target;
	Solution solution;
	res = solution.twosum(numbers, target);	
	cout << " 返回的下标的索引分别为:";


	for(int i = 0; i < 2; i++)
	{
	cout << res[i] << "," 
	}
	return 0;
}


if(!hmap(numbers[i])){
		map.insert(pair<int,int>(numbers[i], i));
这句意思就是如果numbers[i]在map中没有出现过,就将(numbers[i],i)插入到map中,其中numbers[i]相当于key,i相当于value。因为map中的查找是很快的,所以时间复杂度很低。 
另外,map要求其中的key值不允许重复,即一个key只对应一个value。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值