Leetcode - Array - 1. Two Sum (水题,O[n]和O[n^2]实现)

本文解析了一道经典算法题“两数之和”,提供了两种解决方案:一种是时间复杂度为O(n^2)的双层循环遍历方法;另一种是时间复杂度为O(n)的哈希表方法,通过构建哈希表来提高查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Problem Description

 

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.

 

Example:

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

 

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

return [0, 1].

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

 

Subscribe to see which companies asked this question.

 

在给定数组中找到两个数,其和等于给定的value

 

2. My solution(O(n^2)实现) 

太简单了。


class Solution
{
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
        int i=0,j=0;
        int len=nums.size();
        vector<int>result;
        for(i; i<len; i++)
        {
            for(j=0; j<len; j++)
            {
 
                if(i==j)
                    continue;
                if(nums[i]+nums[j]==target)
                {
                    result.push_back(i);
                    result.push_back(j);
                    return result;
                }
            }
        }
        return result;
    }
};


3. My solution2(O(n)实现)

O[n^2]竟然过了,看discuss才发现O[n]的做法,用了hashtable

把每个数在数组中出现的位置用map存起来,这里注意为了判断是否存在这个数,我们把所以index加一,也就是对于[3,2,4]他们在hashtable中的index不是0,1,2而是1,2,3.这样我们就可以用他在hashtable中的index是否为0判断这个数是否存在了。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值