LeetCode 1 Two Sum

题目

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, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法

  • 穷举法
    题目要求在一个数组(无序)中快速找到两个数,使两个数之和等于一个给定的值。题目假设数组中肯定存在至少一组满足要求的数。最直接的方法是使用两个for循环穷举所有可能。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i, j, sum;
        vector<int> idx;
        for (i = 0; i < nums.size()-1; i++) {
            for (j=i+1;j<nums.size();j++) {
                sum = nums[i] + nums[j];
                if(sum == target) {
                    idx.push_back(i);
                    idx.push_back(j);
                    return idx;
                }
            }
        }
        return idx;
    }
};
  • Hash表
    虽然穷举法可以解决,但时间复杂度为O(N*N),在题目的tags看到了Hash Table,考虑用Hash表解决。
    思路是遍历一遍数组,判断当前值是否在Hash表里,不在的话,加入表中(key为数值,value为索引值);如果在的话,在Hash表中查找(target-当前值),如果找到就结束,返回索引值。利用了Hash表中查找元素时间为常数的优势,该方法时间复杂度O(N), 空间复杂度O(N)。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> hmap;
        vector<int> idx;
        for (int i = 0; i < nums.size(); i++) {
            if (!hmap.count(nums[i])) {
                hmap.insert(pair<int,int>(nums[i],i));
            }
            if (hmap.count(target-nums[i])) {
                int j = hmap[target-nums[i]];
                if (j < i) {
                    idx.push_back(j);
                    idx.push_back(i);
                    return idx;
                }
            }
        }
        return idx;
    }
};

每个元素只能使用一次,因此要注意target = 2 * nums[i]的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值