[ LeetCode ] #1. Two Sum (C++ & Python)

题目:

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].

题意

  • 输入一个整数数组nums和一个整数target
  • 输出数组nums中哪两个值相加等于target
  • 假设每一个target仅有一种方案
  • 并且nums中每个值只能使用一次

分析 

这是leetcode中用来入门的第一道题目,Difficulty:Easy, 最最自然的思路是:

 

  1. 首先声明一个 vector<int> ans; 用来保存最终返回的结果
  2. 对nums数组进行遍历,求target与每一个元素的差值
  3. 在上一步求的差值之后,在当前位置之后在一次遍历后面nums剩余元素
  4. 如果查找到相同元素,以此把两个元素的下标插入ans,返回ans,题目完成。否则,继续第一轮遍历
  5. 结果:Runtime: 56 ms, faster than 43.52% of C++ online submissions for Two Sum.

Code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        for(int i=0;i<nums.size();++i){
            int tmp = target-nums[i];
            for(int j=i+1;j<nums.size();j++){
                if(nums[j] == tmp){
                    ans.push_back(i);
                    ans.push_back(j);
                    break;
                }
            }
        }
        return ans;
    }
};

分析

刷题的经验告诉我们,往往最直接的方法性能往往是不尽如人意的(例如冒泡排序),例如上面的代码,我们狂躁的使用两个循环得到最终结果。再翻看论坛之后发现有一些大佬分享了一种更加高效的方法,如下:

完善

这里使用了C++11 新增unordered_map数据结构,从而使得最终的效率大大提升, 分析原因是 前面的双重循环导致了很多不必要的遍历操作,可以直接使用C11中更加高效的数据结构来完善,然后我们得到结果如下:

Runtime: 4 ms, faster than 100% of C++ online submissions for Two Sum.

Improve code

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        unordered_map<int,int> tmp;
        for(int i=0;i<nums.size();++i){
            if(tmp.find(target-nums[i])!=tmp.end()){
                ans.push_back(tmp[target-nums[i]]);
                ans.push_back(i);
                break;
            }else{
                tmp[nums[i]]=i;
            }
        }
        return ans;
    }
};

在以上完善之后,再来使用python复现一下,看下两者差异如何

Python版本

python版本只需要把相应的unordered_map更换为很常用的{ }即可,然后结果如下:

Runtime: 36 ms, faster than 99.71% of Python3 online submissions for Two Sum.

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d={}
        for i in range(len(nums)):
            d[nums[i]]=i
            if target-nums[i] in d and d[target-nums[i]] != i:
                return d[target-nums[i]],i
        for i in range(len(nums)):
            if(target-nums[i] in d and d[target-nums[i]] != i):
                return i,d[target-nums[i]]

Status:  Accepted

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值