[LeetCode]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

第一想法,遍历,如果numbers有n个,第1个和2,3,4,...,n比较,第2个和3,4,5,...,n比较,...,第n-1个和n个比较,当然遇到符合的就退出,复杂度O(n^2)。

立刻意识到不需要遍历,应该用查找,遍历numbers[i]查找numbers里是否有numbers[i]-target,有则退出,否则遍历numbers[i+1].可以自己实现一个简单的平衡二叉查找树,不过直接利用map更方便,key是number。val是index。可是map的key必须是唯一的,numbers有可能有相同的数,从题目中You may assume that each input would have exactly one solution.可以推断,numbers中相同的数最多只可能有2个,所以可以把key改为number*2,遇到重复的,第二个把key记为number*2+1,但这样有个风险,输入的int型有可能溢出,提交尝试了一下,AC。结果的代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        map<int, int> num2index;
        int n = numbers.size();
        vector<int> indexs(2, 0);
        for (int i = 0; i < n; ++i)
        {
            int current = numbers[i];
            if (num2index.find(current<<1)==num2index.end())
            {
                num2index[current<<1] = i+1;
            }
            else
            {
                num2index[(current<<1)+1] = i+1;
            }
        }
        for (auto it = num2index.begin(); it != num2index.end(); ++it)
        {
            int current = (it->first)>>1;
            int left = target - current;
            if (left!=current && num2index.find(left<<1) != num2index.end())
            {
                indexs[0] = it->second;
                indexs[1] = num2index[left<<1];
                break;
            }
            if (left == current && num2index.find(left<<1) != num2index.end())
            {
                if (it->second != num2index[left<<1])
                {
                    indexs[0] = it->second;
                    indexs[1] = num2index[left<<1];
                }
                else
                {
                    indexs[0] = it->second;
                    indexs[1] = num2index[(left<<1)+1];
                }
                break;
            }
        }
        if (indexs[1]<indexs[0])
        {
            int tmp = indexs[0];
            indexs[0] = indexs[1];
            indexs[1] = tmp;
        }
        return indexs;
    }
};

看了一下Dicuss,有牛人的解答,是边构造map边判断,就不需要担心key相同了,思路更清晰,效率更高,且不存在担心int溢出,Java代码如下:

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i + 1;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i + 1);
    }
    return result;
}

 

转载于:https://www.cnblogs.com/yezhangxiang/p/3923588.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值