[Leetcode 1, Medium] Two sum

Problem:

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

Analysis:

The brute-force method is straightforward and its time complexity is O(n^2).

The second method is to use sorting. Since this quesiton requires the indices of two elements whose sum is equal to the target, we cannot sort the original array. An alternative  way is to create a new array, each element of which is a pair of the value of element and it index. Sort this new array and use the linear search (O(n)). This method keeps the information of index of every element, the result is the collection of the second turples of two elements we found.

Note: Here, the binary search does not apply this case, since it needs to apply it every difference between the target value with an element (trasversal from the last element to the second one). The total time complexity is O(nlog n). This means that a binary search is better to use the case that search one given element but not a series of ones.

Note: The std::sort is not a stable sort. Then, we always need to sort the result.

The third method is to use Hash map. The time complexity of this method is O(n) and it needs an extra space complexity of O(n). The basic idea is as follows: Check the key target - nums[i] exists in the map. If yes, return the array of indices; if not, add nums[i] as a new key and i as the value.

There are two tricks here need to notice: (1) We should deal with the problem by two cases: target is odd or even: for the latter case, we need to check whether the size of the slot of target / 2 is bigger than or equal to 2; (2) If we only need to test such sum exists, we do not need to count the number of elements of each slot: we only need to test the number is not samller than 2. (This avoid the overflowwing of int.)

Code:

C++:

Solution 1 (Brute-force): This method cannot pass the large-data test.

 1     vector<int> twoSum(vector<int>& nums, int target) {
 2         vector<int> result;
 3         if(nums.empty())
 4             return result;
 5
 6         for(int i = 0; i < nums.size(); ++i) {
 7             for(int j = i; j < nums.size(); ++j) {
 8                 if(target == nums[i] + nums[j]) {
 9                     result.push_back(i);
10                     result.push_back(j);
11                     break;
12                 }
13             }
14         }
15
16         return result;
17     }

Solution 2 (Sorting): (16 ms, not the fastest one: 8 or 12?)

 1     static bool CompareFunction(pair<int, int>& left, pair<int, int>& right)
 2     {
 3         return left.first <= right.first;
 4     }
 5
 6     vector<int> twoSum(vector<int>& nums, int target) {
 7         vector<int> result;
 8         if(nums.empty())
 9             return result;
10
11         vector<pair<int, int> > nums_index;
12         for(int i = 0; i < nums.size(); ++i)
13             nums_index.push_back(make_pair(nums[i], i));
14
15         sort(nums_index.begin(), nums_index.end(), CompareFunction);
16
17         int start = 0;
18         int end = nums_index.size() - 1;
19         while(start < end) {
20             if(nums_index[start].first + nums_index[end].first == target) {
21                 result.push_back(min(nums_index[start].second, nums_index[end].second) + 1);
22                 result.push_back(max(nums_index[start].second, nums_index[end].second) + 1);
23                 return result;
24             } else if(nums_index[start].first + nums_index[end].first < target)
25                 for(++start; start < end && nums_index[start].first == nums_index[start - 1].first; ++start);
26             else
27                 for(--end; start < end && nums_index[end].first == nums_index[end + 1].first; --end);
28
29         }
30
31         return result;
32     }

Solution 3 (Hash table):

 1     vector<int> twoSum(vector<int> &nums, int target) {
 2         map<int, int> h;
 3         for(int i = 0; i < nums.size(); ++i) {
 4             if(h.find(target - nums[i]) != h.end()) {
 5                 vector<int> result(1, h[target - nums[i]] + 1);
 6                 result.push_back(i + 1);
 7                 return result;
 8             }
 9             h[nums[i]] = i;
10         }
11     }
时间: 2024-10-25 18:00:32

[Leetcode 1, Medium] Two sum的相关文章

LeetCode --- 64. Minimum Path Sum

题目链接:Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 这道题的要求是在m*n

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

leetcode --day12 Surrounded Regions &amp; Sum Root to Leaf Numbers &amp; Longest Consecutive Sequence

1.  Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your fu

leetcode 练习1 two sum

leetcode 练习1  two sum [email protected] 问题描述 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. Example: Given nums = [2, 7, 11, 15

[LeetCode] Minimum Size Subarray Sum 解题思路

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7,the subarray [4,3] has the minimal

leetcode第一刷_Combination Sum Combination Sum II

啊啊啊啊,好怀念这种用递归保存路径然后打印出来的题目啊,好久没遇到了. 分了两种,一种是可以重复使用数组中数字的,一种是每个数字只能用一次的.其实没有多大区别,第一种每次进入递归的时候都要从头开始尝试,第二种要找一个标记的数组,把已经用到过的排除掉,就像生成全排列时的做法一样.跟我一样用引用保存中间结果的话,要注意回退的情况.第二种回退时,要把用到的那个数也恢复为可用,就完全像全排列时做的一样.破例贴两个题的代码,因为他们是在是不值得用两片文章来写. class Solution { publi

【一天一道LeetCode】#113. Path Sum II

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22,

leetcode第一刷_Path Sum II

测试策略:静态测试还是动态测试? [对话场景] 成功发布某个软件版本之后,项目团队召开了项目的经验教训总结大会.在会议期间,项目经理小项和测试经理小测进行了如下的对话: 小项:"小测,我们的项目时间压力很大,测试执行是我们的关键路径,测试团队是否可以在测试执行阶段投入更多的人力和物力?"限定时间和人力资源同等条件. 小测:"啊!假如增加我们的测试执行时间,在整个周期不变的情况下,我们就需要压缩前期的学习和评审投入的时间和工作量,是吗?" 小项:"是的,你看

Leetcode 线性表 Two Sum

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Two Sum Total Accepted: 19206 Total Submissions: 103959 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