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

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

【Problem:】

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, and you may not use the same element twice.

 

【Example】

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

 

【Solution】

1)-----------Submission Status :Time Limit Exceeded

Time complexity:O(n^2)2​​).

【Python】 import timeclass Solution(object):    def twoSum(self,nums,target):        for i in range(len(nums)):            for j in range(i+1,len(nums)):                if nums[i]+nums[j]==target:                    return i,jstart = time.clock()test=Solution()nums=[1,2,3,4,5,55,26,25,36,211,200,300,258,459]target=8print("The indices are :",test.twoSum(nums,target))end = time.clock()c=end-startprint("Runtime is :",c)

 

可是 Java 的这个,Time complexity 也是O(n^2)2 ,却可以 AC??

【Java】 public int[] twoSum(int[] nums, int target) {    for (int i = 0; i < nums.length; i++) {        for (int j = i + 1; j < nums.length; j++) {            if (nums[j] == target - nums[i]) {                return new int[] { i, j };            }        }    }    throw new IllegalArgumentException("No two sum solution");}

 

2)两个方法做个对比:(Python 语言)

#----class Solution(object):    # Method 1 : O(n_2)    def twoSum1(self,nums,target):        for i in range(len(nums)):            for j in range(i+1,len(nums)):                if nums[i]+nums[j]==target:                    return i,j    # Method 2 : O(n)    def twoSum2(self, nums, target):            if len(nums) <= 1:                return False            buff_dict = {}            for i in range(len(nums)):                if nums[i] in buff_dict:                    return [buff_dict[nums[i]], i]                else:                    buff_dict[target - nums[i]] = itest=Solution()nums=[1,2,3,4,5,55,26,25,36]target=8start1 = time.clock()print("The indices of method1 are :",test.twoSum2(nums,target))end1 = time.clock()t1=end1-start1print("Runtime1 is :",t1)start2 = time.clock()print("The indices of method2 are :",test.twoSum2(nums,target))end2 = time.clock()t2=end2-start2print("Runtime2 is :",t2)

结果是:

 

3)外加一个方法3 ,会比法2好些?(亦可AC)

#----class Solution(object):    # Method 1 : O(n_2)    def twoSum1(self,nums,target):        for i in range(len(nums)):            for j in range(i+1,len(nums)):                if nums[i]+nums[j]==target:                    return i,j    # Method 2 : O(n)    def twoSum2(self, nums, target):            if len(nums) <= 1:                return False            buff_dict = {}            for i in range(len(nums)):                if nums[i] in buff_dict:                    return [buff_dict[nums[i]], i]                else:                    buff_dict[target - nums[i]] = i    def twoSum3(self, num, target):            tmp_num = {}            for i in range(len(num)):                if target - num[i] in tmp_num:                    # here do not need to deal with the condition i = target-i                    return (tmp_num[target-num[i]], i)                else:                    tmp_num[num[i]] = i            return (-1, -1)test=Solution()nums=[1,2,3,4,5,55,26,25,36]target=8start1 = time.clock()print("The indices of method1 are :",test.twoSum2(nums,target))end1 = time.clock()t1=end1-start1print("Runtime1 is :",t1)start2 = time.clock()print("The indices of method2 are :",test.twoSum2(nums,target))end2 = time.clock()t2=end2-start2print("Runtime2 is :",t2)start3 = time.clock()print("The indices of method3 are :",test.twoSum3(nums,target))end3 = time.clock()t3=end3-start3print("Runtime3 is :",t3)

结果是:

 

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

你可能感兴趣的文章
洛谷P1111 修复公路 并查集 图论 最小生成树
查看>>
微名汇-微信公众平台功能开发(微信聊天机器人)
查看>>
A2W和W2A :很好的多字节和宽字节字符串的转换宏
查看>>
我个人的javascript和css命名规范
查看>>
kylin的安装与配置
查看>>
Android Intent的setClass和setClassName的区别
查看>>
php-fpm nginx 使用 curl 请求 https 出现 502 错误
查看>>
西宁海关首次对外展示截获500余件有害生物标本
查看>>
泸州移动能源产业园首片薄膜电池组件成功下线
查看>>
韩国瑜会见陆委会主委陈明通:别给高雄念紧箍咒
查看>>
交通部:加大人工售票力度保障农民工春运出行
查看>>
物联网的学术层、应用层和行为层的基本介绍
查看>>
初探github(一)
查看>>
源码分析之 LinkedList
查看>>
免SDK实现微信/支付宝转账打赏功能
查看>>
安卓.9图片制作
查看>>
MySQL 高可用性keepalived+mysql双主
查看>>
Python环境安装及数据基本预处理-大数据ML样本集案例实战
查看>>
【详解】TiDB 2.0 GA is here !
查看>>
iOS开发-模拟网络环境
查看>>