随笔- 509  文章- 0  评论- 151  阅读- 22万 

LeetCode - Two Sum

2013.12.1 02:30

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

 

Solution:

  For an array of integers and a target value, find out the pair of numbers in the array that add up to the target.

  My first solution is simply brute-force, for each element a[i], check if there exists a[j] in a[i + 1 : n] such that a[i] + a[j] == target.

  Obviously, the time complexity is O(n^2) with double for-loop, while space complexity is O(1).

Accepted code:

复制代码
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         result.clear();
 7         
 8         int i, j, n;
 9         
10         n = numbers.size();
11         for(i = 0; i < n; ++i){
12             for(j = i + 1; j < n; ++j){
13                 if(numbers[i] + numbers[j] == target){
14                     result.push_back(i + 1);
15                     result.push_back(j + 1);
16                     break;
17                 }
18             }
19             if(j < n){
20                 break;
21             }
22         }
23         
24         return result;
25     }
26 private:
27     vector<int> result;
28 };
复制代码

  So the array is not sorted, why not sort it and use binary search for a faster solution? Let's do this with index sorting algorithm.

  If the data is sorted, we can easily use binary search to find the solution with O(n * log(n)) time, but unable to guarantee that index1 < index2.

  Thus we preserve the original data and use another array to record the indices, and sort this index array. Index sorting requires a sorting comparator, called by sort() function. I used global data for the sake of convenience, otherwise an efficient sorting algorithm must be written inside the class. Time complexity is O(n * log(n)), both in sorting and searching. Space compexity is O(n), with the $index array, and the global $data array.

Accepted code:

复制代码
 1 #include <algorithm>
 2 using namespace std;
 3 
 4 vector<int> data;
 5 bool sort_comparator(const int &x, const int &y)
 6 {
 7     return data[x] < data[y];
 8 }
 9 
10 class Solution {
11 public:
12     vector<int> twoSum(vector<int> &numbers, int target) {
13         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         result.clear();
16         index.clear();
17         data.clear();
18         data = numbers;
19         
20         int i, j, n;
21         
22         n = numbers.size();
23         if(n < 2){
24             return result;
25         }
26         for(i = 0; i < n; ++i){
27             index.push_back(i);
28         }
29         sort(index.begin(), index.end(), sort_comparator);
30         
31         int ll, rr, mm;
32         for(i = 0; i < n; ++i){
33             ll = i + 1;
34             rr = n - 1;
35             if(ll > rr || target - data[index[i]] < data[index[ll]] || target - data[index[i]] > data[index[rr]]){
36                 continue;
37             }
38             while(ll <= rr){
39                 mm = (ll + rr) / 2;
40                 if(target - data[index[i]] < data[index[mm]]){
41                     rr = mm - 1;
42                 }else if(target - data[index[i]] > data[index[mm]]){
43                     ll = mm + 1;
44                 }else{
45                     if(index[i] < index[mm]){
46                         result.push_back(index[i] + 1);
47                         result.push_back(index[mm] + 1);
48                     }else{
49                         result.push_back(index[mm] + 1);
50                         result.push_back(index[i] + 1);
51                     }
52                     break;
53                 }
54             }
55             if(ll <= rr){
56                 break;
57             }
58         }
59         
60         index.clear();
61         data.clear();
62         return result;
63     }
64 private:
65     vector<int> result;
66     vector<int> index;
67 };
复制代码

 

 posted on   zhuli19901106  阅读(547)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示