LeetCode 1 # TwoSum

LeetCode 1 # TwoSum

很有意思的问题.

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)

这第一种解法很"幼稚".确实很简单,但是面试的时候如果写出这东西就跪稳了...算法的时间复杂度是 O(n2)

如果提前把输入数据放到hash表里面去,时间复杂度是 O(n) 然后再遍历输入数据,检查 target - num[i]是否可以索引,如果可以,就证明元素存在.思路就是(target - num[i]) + num[i] = target

"""
    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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值