【leetcode】 two sum

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


解决方案1:排序完从两端开始夹逼,时间复杂度O(nlogn)。排序O(nlogn), 查找O(n).但是结果必须输出index,所以此方案不成立

解决方案2:穷举遍历,时间复杂度O(n2)

解决方案3:用哈希表存储,然后遍历

因为unordered_map的查找时间复杂度为O(logn),所以此算法时间复杂度为O(nlogn)

//解决方案3
class Solution {
public:
    vector<int> twoSum(vector<int>& num, int target) {
        unordered_map <int, int> mapping;
        vector <int> result;
        
        for (int i = 0; i < num.size(); ++i) {
            mapping[num[i]] = i;
        }
        
        for (int i = 0; i < num.size(); ++i) {
            const int cmp = target - num[i];
            
            //find(key)
            //如果mapping.find() == mapping.end() 则说明未找到
            if (mapping.find(cmp) != mapping.end() && mapping[cmp] > i) {
                result.push_back(i + 1);
                result.push_back(mapping[cmp] + 1);
                break;
            }
        }
        
        return result;
    }
};

解决方案4:假设输入的值范围在-/+ 40000,可以用如下方法解决

以空间换时间的方式。时间复杂度O(n)

//解决方案4

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

解决方案4属于投机取巧的方法,不过在我之前面试时碰到的一个题目是给定范围让你排序或者查找个数,其实也可以利用到解决方案4的方法。

引用:

https://github.com/soulmachine/leetcode 

https://leetcode.com/discuss/57223/my-code-beats-99%25-8ms-using-c


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值