【leetcode】1. Two Sum

本文解析了一道经典算法题“两数之和”,介绍了两种解决方案:双层循环法和利用哈希表的方法。通过对比,展示了如何将时间复杂度从O(n^2)优化至O(n),并附带了C++实现代码。

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

一、题目描述

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.


题目解读:给一个整数序列和一个目标值,找出序列中两个数加起来等于目标值,返回这两个数在序列中的下标


思路:一开始只能想到写两个for循环遍历


c++代码(758ms,11.48%) 就这样还能排到11%呢  = = ! 汗....

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        int left,right;
        for(left=0; left<nums.size(); left++){
            for(right = left+1; right<nums.size(); right++){
                if((nums[left]+nums[right]) == target){
                    result.push_back(left);
                    result.push_back(right);
                    return result;
                }//if
            }//for
        }//for
        return result;
    }
};


看讨论区别人的代码,在遍历的同时使用map存储已遍历过的数的位置,以便于快速查找,时间复杂度可以达到o(n)

c++代码(16ms,62.06%)

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        //Key is the number and value is its index in the vector.
        	unordered_map<int, int> hash;
        	vector<int> result;
        	for (int i = 0; i < numbers.size(); i++) {
        		int numberToFind = target - numbers[i];
        
                    //if numberToFind is found in map, return them
        		if (hash.find(numberToFind) != hash.end()) {
                            //+1 because indices are NOT zero based
        			result.push_back(hash[numberToFind]);
        			result.push_back(i);			
        			return result;
        		}
        
                    //number was not found. Put it in the map.
        		hash[numbers[i]] = i;
        	}
        	return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值