标签:
很有意思的问题.
Two Sum Total Accepted: 63448 Total Submissions: 350576 My Submissions Question Solution
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
嘛,弱弱我一开始向导的想法是介个样子的.
"""
Code writer : EOF
Code file : ts.py
Code date : 2015.02.15
Code description :
This is a solution for Leetcode problem-1 @Two Sum
"""
class Solution() :
def twoSum(self, num, target):
if num is None or target is None:
return
for i in range(0, len(num)) :
for j in range(i + 1, len(num)) :
if num[i] + num[j] == target :
return (i+1, j+1)
#------testing-------
#numbers = [2,7,11,15]
numbers = [-1, -2, -3, -4, -5]
target = -8
print "Input :"
print "numbers= ", numbers, "target = ", target
s = Solution()
print "Output", s.twoSum(numbers, target)
这第一种解法很"幼稚".确实很简单,但是面试的时候如果写出这东西就跪稳了...算法的时间复杂度是
如果提前把输入数据放到hash表里面去,时间复杂度是
"""
Code writer : EOF
Code file : ts_2.py
Code date : 2015.02.15
Code description :
This is a solution for Leetcode problem-1 @Two Sum
"""
class Solution() :
def twoSum(self, num, target):
if num is None or target is None:
return
dic = {}
for i in range(0, len(num)) :
dic[num[i]] = i
for i in range(0, len(num)) :
if target - num[i] in dic and i is not dic[target- num[i]]:
return (i + 1, dic[target- num[i]] + 1)
#------testing-------
#numbers = [2,7,11,15]
numbers = [3, 2, 4]
#numbers = [-1, -2, -3, -4, -5]
target = 6
print "Input :"
print "numbers= ", numbers, "target = ", target
s = Solution()
print "Output", s.twoSum(numbers, target)
Leetcode 给出的题解分析: O(n2) runtime, O(1) space – Brute force: The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2). O(n) runtime, O(n) space – Hash table: We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
下面是陈皓的解答,学习
// Source : https://oj.leetcode.com/problems/two-sum/
// Author : Hao Chen
// Date : 2014-06-17
/**********************************************************************************
*
* 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
*
*
**********************************************************************************/
class Solution {
public:
/*
* The easy solution is O(n^2) run-time complexity.
* ```
* foreach(item1 in array) {
* foreach(item2 in array){
* if (item1 + item2 == target) {
* return result
* }
* }
* ```
*
* We can see the nested loop just for searching,
* So, we can use a hashmap to reduce the searching time complexity from O(n) to O(1)
* (the map‘s `key` is the number, the `value` is the position)
*
* But be careful, if there are duplication numbers in array,
* how the map store the positions for all of same numbers?
*
*/
//
// The implementation as below is bit tricky. but not difficult to understand
//
// 1) Traverse the array one by one
// 2) just put the `target - num[i]`(not `num[i]`) into the map
// so, when we checking the next num[i], if we found it is exisited in the map.
// which means we found the second one.
//
vector<int> twoSum(vector<int> &numbers, int target) {
map<int, int> m;
vector<int> result;
for(int i=0; i<numbers.size(); i++){
// not found the second one
if (m.find(numbers[i])==m.end() ) {
// store the first one poisition into the second one‘s key
m[target - numbers[i]] = i;
}else {
// found the second one
result.push_back(m[numbers[i]]+1);
result.push_back(i+1);
break;
}
}
return result;
}
};
标签:
原文地址:http://blog.csdn.net/cinmyheart/article/details/43840305