[leetcode刷题 C++] 1. Two Sum

[leetcode刷题 C++] 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].
    
  • 思路

  1. O(n^2) 遍历每个元素x,查看在给定的数组中是否有数值等于target-x

    最开始想到的就是这个方法。代码如下:

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int>::iterator it;
            vector<int> dummy;
            for(it = nums.begin(); it != nums.end(); it++) {
                for(auto jt = it+1; jt != nums.end(); jt++) {
                    if(*it + *jt == target) {
                    	return vector<int>{it - nums.begin(), jt - nums.begin()}
                    }
                }
            }
            return dummy;
        }
    };
    
  2. O(n) 使用hash表省去寻找(target - x)的时间

    要将时间复杂度从O(n^2)降低到O(n),就需要减少寻找(target - x)的时间,即从数组中查找某一个元素的时间,那么很自然的就想到了hash表,查找的平均复杂度为O(1)。所以在使用hash表后,整体的时间复杂度可以为O(n)。
    其中,unordered_map是使用hash表实现的:https://blog.csdn.net/hk2291976/article/details/51037095

    代码如下:

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> hash_tbl;
            vector<int>::iterator it;
            unordered_map<int, int>::const_iterator found_it;
            vector<int> dummy;
            
            for(it = nums.begin(); it != nums.end(); it++) {
                found_it = hash_tbl.find(target - *it);
                if(found_it != hash_tbl.end()) {
                    return vector<int>{found_it->second, it - nums.begin()};
                } else {
                    hash_tbl.insert({*it, it-nums.begin()});
                }
            }        
            return dummy;
        }
    };
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值