LeetCode题解——Two Sum

题目地址:https://oj.leetcode.com/problems/two-sum/

 

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

 

题目大意:

给定一个数组,找出其中两个数,它们的和等于给定的值。

函数返回这两个数的“下标”,下标按序排列,从1开始计算。

每个输入有且只有一个解。

 

分析:

①暴力解法。

  求每两个元素的和,时间为O(n2)。

②先排序,后查找 或者 左右夹逼。

  排序时间O(n logn),由于需要记录下标和元素值的关系,空间复杂度O(n)。然后:

  查找:对每一个元素a,二分查找target - a是否存在。总时间为O(n logn) + O(n logn) = O(n logn);

  夹逼:利用一对首尾指针求和,和<target,则首指针右移;和>target,则尾指针左移;相等则返回记录的下标值。总时间为O(n logn) + O(n) = O(n logn)。

③利用哈希表查找。

  哈希表记录元素对应下标,对于元素a,O(1)时间查找target - a是否存在。总时间为O(n)。

 

程序挂掉的几个测试用例

[5, 75, 25]  100      //排序之后下标顺序问题
[3, 2, 4]      6         //3 + 3 == 2 + 4  同一个元素被计算两次
[0, 4, 3, 0]  0         //0 + 0   元素重复,哈希表覆盖

 

代码: 

  1 #include <iostream>
  2 #include <vector>
  3 #include <algorithm>
  4 #include <tr1/unordered_map>
  5 using namespace std;
  6 using namespace tr1;
  7 
  8 //②先排序,再夹逼。用一个辅助struct来记录数据和下标信息,并自定义比较函数,来对struct数组排序。
  9 struct node{
 10     int data;
 11     int index;
 12     node(int _data, int _index): data(_data), index(_index)
 13     {
 14     }
 15 };
 16 
 17 bool myCmp(node n1, node n2)
 18 {
 19     return n1.data < n2.data;
 20 }
 21 
 22 vector<int> twoSum1(const vector<int> &numbers, int target)
 23 {
 24     vector<int> result;
 25 
 26     if(numbers.empty())
 27     {
 28         return result;    
 29     }
 30 
 31     vector<node> nv;   //space: O(N)
 32     for(int i = 0; i < numbers.size(); ++i)  //time: O(N)
 33     {
 34         nv.push_back( node(numbers[i], i) );
 35     }
 36 
 37     sort(nv.begin(), nv.end(), myCmp);  //排序,time: O(NlgN)
 38     
 39     int hIdx = 0, tIdx = nv.size() - 1;
 40 
 41     while(hIdx < tIdx)  //夹逼,time: O(N)
 42     {
 43         int sum = nv[hIdx].data + nv[tIdx].data;
 44 
 45         if(sum == target)
 46         {
 47             result.push_back(min(nv[hIdx].index, nv[tIdx].index) + 1);//min、max来确保下标顺序
 48             result.push_back(max(nv[hIdx].index, nv[tIdx].index) + 1);
 49             break;
 50         }
 51         else if(sum < target)
 52         {
 53             ++hIdx;
 54         }
 55         else
 56         {
 57             --tIdx;
 58         }
 59     } //while
 60 
 61     return result;
 62 }
 63 
 64 //③哈希表,由数据映射到下标,相同数据只记录最后一个下标。
 65 vector<int> twoSum2(const vector<int> &numbers, int target)
 66 {
 67     vector<int> result;
 68 
 69     if(numbers.empty())
 70     {
 71         return result;
 72     }
 73 
 74     unordered_map<int, int> num2loc;  //space: O(N)
 75     for(int i = 0; i < numbers.size(); ++i)  //哈希映射,time: O(N)
 76     {
 77         num2loc[ numbers[i] ] = i;
 78     }
 79 
 80     for(int i = 0; i < numbers.size() - 1; ++i)  //查找,time: O(N)
 81     {
 82         int gap = target - numbers[i];
 83 
 84         if( num2loc.find(gap) != num2loc.end() && num2loc[gap] > i )
 85         {
 86             result.push_back(i + 1);
 87             result.push_back(num2loc[gap] + 1);
 88             break;
 89         }
 90     }
 91 
 92     return result;
 93 }
 94 
 95 int main()
 96 {
 97     int nums[] = {0,4,3,0};
 98     vector<int> numbers(nums, nums + sizeof(nums)/sizeof(*nums));
 99     int target = 0;
100 
101     vector<int> result;
102 
103     result = twoSum1(numbers, target);
104     for(int i = 0; i < result.size(); ++i)
105     {
106         cout << result[i] << ' ';
107     }
108     cout << endl;
109 
110     result = twoSum2(numbers, target);
111     for(int i = 0; i < result.size(); ++i)
112     {
113         cout << result[i] << ' ';
114     }
115     cout << endl;
116 
117     return 0;
118 }

  

转载于:https://www.cnblogs.com/qieerbushejinshikelou/p/3792295.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值