LeetCode 题解(55): Two Sum

本文探讨了如何在整数数组中寻找两个数使它们的和等于特定目标值的问题。提出了两种解决方案,一种使用排序与双指针技术,时间复杂度为O(n log n),另一种利用哈希表实现O(n)的时间复杂度。

题目:

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

题解:

用了个vector<pair<int, int>>来记录数和该数的位置。自写排序比较函数,然后对vector<pair<int, int>>针对第一个int的大小排序。最后前后端扫描求和。时间复杂度O(nlgn)。空间复杂度O(2n)。

c++版:

bool compare(const pair<int, int> a, const pair<int, int> b) {
    return a.first < b.first;
}

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<pair<int, int>> temp;
        for(int i = 0; i < numbers.size(); i++) {
            temp.push_back(pair<int, int>(numbers[i], i+1));
        }
        vector<int> result;

        sort(temp.begin(), temp.end(), compare);
        
        int begin = 0, end = numbers.size()-1;
        while(begin < end) {
            if(temp[begin].first + temp[end].first == target) {
                if(temp[begin].second < temp[end].second) {
                    result.push_back(temp[begin].second);
                    result.push_back(temp[end].second);
                    break;
                } else {
                    result.push_back(temp[end].second);
                    result.push_back(temp[begin].second);
                    break;
                }
            } else if(temp[begin].first + temp[end].first > target){
                end--;
            } else 
                begin++;
        }
        return result;
    }
};

网上学来O(n)的解法,定义一个map<int, int>记录当前数的余数和当前数的位置。检查每一个数,如果在map里,说明曾经有数需要该数作为余数,返回该数和曾经的数的位置。
Java版:

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

Python版:

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        d = {}
        for i in range(0,len(num)):
            if d.has_key(num[i]) == False:
                d[target - num[i]] = i + 1
            else:
                index1 = d[num[i]]
                index2 = i + 1
        return (index1, index2)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值