LeetCode-Array-1. Two Sum

来源:互联网 发布:域名备案需要多少钱 编辑:程序博客网 时间:2024/05/01 14:19

问题:https://leetcode.com/problems/two-sum/

Given an array of integers, return indicesof the two numbers such that they add up to a specific target.You may assumethat 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].

给定一个数组和一个值,找数组中两个元素加起来和是这个值的索引。

思考1:用两个for循环,很容易解出问题,但是消耗时间长,O(n2)的复杂度。注意要用一个数组来放索引值。

代码1


思考2:现在想用更小的时间复杂度解题,既然优化了时间复杂度,就要牺牲空间复杂度,是用stack?queue?vector?还是hash_map?对于stack和queue,除了pop外,查找的时间复杂度也是O(n),而hash_map最理想的情况下时间复杂度是O(1)。现将数组中所有的元素都存到hash_map中,一次循环,时间复杂度是O(n)。用一个<number, index>的map, 记录每个一字出现的位置。逐个去检查数字,看看他要凑成对的那个数字是不是已经存在了即可。map里直接存的是要去找的那个数。比如target=9, 现在在位置0遇到了2,那存一个map[9-2]=0,然后检查的时候就可以直接去keys里面找有没有7了。

代码2:



0 0
原创粉丝点击