【LeetCode】1. Two Sum

今天,想看看LeetCode的第一题是啥,感觉挺有意思,就做了。

题目描述

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.

例子

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路

(1)双重循环,找到两个相加结果为target的数。这种方法效率不高,时间复杂度为O(n^2)。

(2)只需要一次遍历,通过使用hashmap,将时间复杂度缩减为O(n)。

实现过程

创建<value, index>的hashmap,然后遍历 numbers 数组。
如果 numbers[i] 在hashmap中可以找到与之配对的 target-numbers[i] 这个键值,那么结束遍历,返回这两个数的下标;
如果在hashmap中没有找到 target-numbers[i] ,则将 <numbers[i] ,i> 加入到hashmap中,继续遍历。
这样,将遍历过的元素存入hashmap中,不需要重复遍历。

代码

方法(1)

vector<int> twoSum(vector<int> &numbers, int target) {
    vector<int> result;
    for (int i = 0; i < numbers.size(); i++) {
        int val = target - numbers[i];
        for (int j = i+1; j < numbers.size(); j++) {
            if (numbers[j] == val) {
                result.push_back(i);
                result.push_back(j);
                return result;
            }
        }
    }
}

方法(2)

vector<int> twoSum(vector<int> &numbers, int target) {
    unordered_map<int, int> hashMap;
    vector<int> result;
    int val;
    for (int i = 0; i < numbers.size(); i++) {
        val = target - numbers[i];
        if (hashMap.find(val) != hashMap.end()) {
            result.push_back(hashMap[val]);
            result.push_back(i);            
            return result;
        }
        hashMap[numbers[i]] = i;
    }
    return result;
}
时间对比

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值