LeeCode编程训练日记一:Two Sum

来源:互联网 发布:警察查封淘宝假章 编辑:程序博客网 时间:2024/05/21 15:44

通过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。




原创粉丝点击