博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 01 Two Sum
阅读量:4150 次
发布时间:2019-05-25

本文共 1067 字,大约阅读时间需要 3 分钟。

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

此题乍一看很简单,只要遍历数组,需找target-numbers[i]的元素即可,算法复杂度为O(n*n),但这样是会超时,不被接受。该方法需要多次扫描数组,而每次扫描的信息又没有被记住,造成信息的浪费。

最好的方法是能够扫描一次,但能够记住每个元素的位置。因此可以使用C++的map类。

第一次扫描,将每个元素及其坐标加入到map中。

第二次扫描,在map中查找target-numbers[i]的元素,要注意target = 2*numbers[i]的情形。map底层是基于红-黑树的,查找复杂度可以认为是O(1)。

这样整个算法的时间复杂度可以认为是O(n).

class Solution {public:    vector
twoSum(vector
&numbers, int target) { vector
out; map
hash_map; int tmp ; int index; size_t length = numbers.size(); for (int i =0; i
(numbers[i], i)); //} } for (int i =0; i

转载地址:http://lyxti.baihongyu.com/

你可能感兴趣的文章
MySQL-数据库、数据表结构操作(SQL)
查看>>
OpenLDAP for Windows 安装手册(2.4.26版)
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
JSP的内置对象及方法
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Spring MVC和Struts2的比较
查看>>
Hibernate和IBatis对比
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Android 的source (需安装 git repo)
查看>>
Commit our mod to our own repo server
查看>>
LOCAL_PRELINK_MODULE和prelink-linux-arm.map
查看>>
Simple Guide to use the gdb tool in Android environment
查看>>
Netconsole to capture the log
查看>>
Build GingerBread on 32 bit machine.
查看>>
How to make SD Card world wide writable
查看>>
Detecting Memory Leaks in Kernel
查看>>