Add Two Numbers

本文介绍了一种高效的方法来解决寻找数组中和为目标数的两个元素的问题,通过使用哈希表来实现O(n)的时间复杂度。

Number of 1 Bits

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

For example

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

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


思路

最简单的2重循环,自己也是这样想的


代码1 –2重循环

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        for(size_t it = 0;it<nums.size()-1;it++)
        {
            for(size_t it2 = it+1;it2<nums.size();it2++)
            {
                if(nums[it]+nums[it2]==target)
                {
                    res.push_back(it);
                    res.push_back(it2);
                    return res;
                }

            }
        }

    }
};


代码2 –O(n)

用到了map,存nums[x],x
然后就在里面找target-nums[x]
这样找到第二个的时候,第一个肯定是配对好的了

    public int[] twoSum(int[] nums, int target) {

        if(nums==null || nums.length==0)
            return null;
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int x=0;x<nums.length;x++){
            if(map.containsKey(target-nums[x])){
              result[1] = x;
              result[0] = map.get(target-nums[x]);
            }
            map.put(nums[x],x);
        }
        return result;
    } };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值