博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Lintcode]56. Two Sum
阅读量:5242 次
发布时间:2019-06-14

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

Description

  1. Two Sum
    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 zero-based.

Example

numbers=[2, 7, 11, 15], target=9

return [0, 1]

Challenge

Either of the following solutions are acceptable:

O(n) Space, O(nlogn) Time

O(n) Space, O(n) Time
Notice
You may assume that each input would have exactly one solution

我的代码

class Solution:    """    @param numbers: An array of Integer    @param target: target = numbers[index1] + numbers[index2]    @return: [index1, index2] (index1 < index2)    """    def twoSum(self, nums, target):        # write your code here        for i in range(len(nums)):            if 2*nums[i] == target:                nums[i] += 1                try:                    return [i, nums.index(target - nums[i]+1)]                except:                    nums[i] -= 1                    continue            try:                return [i,nums.index(target-nums[i])]            except:                continue

法二

def twoSum(self, nums, target):    # write your code here    res = {
} for i,item in enumerate(nums): if target - item in res.keys(): return [res[target-item],i] else: res[item] = i

思路:

1.之前没考虑target/2的情况

2.没考虑两个相同的数字的情况,就很野蛮地直接排除了target/2的情况,结果少了[3,3] 6的情况
3.list 的index的时间复杂度是O(n),所以这个的时间复杂度是O(n^2), 用dict查询的话,利用的是hash table,理想情况下,时间复杂度是O(1),整体时间复杂度是O(n).

法二更简单。不用考虑target/2的情况

转载于:https://www.cnblogs.com/siriusli/p/10353408.html

你可能感兴趣的文章
python安装easy_intall和pip
查看>>
HDU1004
查看>>
MySQL高速缓存
查看>>
DropdownList绑定的两种方法
查看>>
价值观
查看>>
数值计算中,浮点类型给我们挖的坑
查看>>
(String)、toString、String.valueOf
查看>>
mongodb命令----批量更改文档字段名
查看>>
python多线程下载网页图片并保存至特定目录
查看>>
《人工智能的未来》--------------经典语录
查看>>
了解循环队列的实现
查看>>
CentOS 简单命令
查看>>
Linux中修改docker镜像源及安装docker
查看>>
数位dp(模板+例题)
查看>>
javascript中强制类型转换
查看>>
python学习笔记
查看>>
php+ajax(jquery)的文件异步上传
查看>>
使用&nbsp;SharedPreferences 分类: Andro...
查看>>
TLA+(待续...)
查看>>
c#数据结构(第四章)
查看>>