早就想刷LeetCode了,但一直在拖,新学期开学,开始刷算法。

我准备从Python和C++两种语言刷。一方面我想做机器学习,以后用Python会比较多,联系一下。另一方面C++或者C语言更接近底层,能够让我更深入的理解算法。

1、题目

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]

2、Python解法

我是这样写的

class Solution(object):
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j nums=[2,7,11,15]
target=9
result=Solution()
result_num=result.twoSum(nums,target)
print(result_num)

其中遇到了一个错误

TypeError: twoSum() missing 1 required positional argument: 'target'

这个因为之前我后面几行的代码是

 nums=[2,7,11,15]
target=9
result_num=Solution.twoSum(nums,target)
print(result_num)

没有初始化Solution类,改成上面第23行先初始化一下就行了

然而。。。这个代码完全不能通过LeetCode的测试。算法复杂度太高

然后我看了别人写的

 class Solution(object):
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
result = {}
if n <= 1:
return False
else:
for i in range(n):
if nums[i] in result:
return result[nums[i]],i
else :
result[target-nums[i]]=i nums=[2,7,11,15]
target=9
result=Solution()
result_num=result.twoSum(nums,target)
print(result_num)

就是借用字典的key-value进行的匹配,算法复杂度仅为O(n)

然后还看到了这个

 class Solution(object):
def twoSum(self, nums, target): for ind, num in enumerate(nums):
if target-num in nums and nums.index(target-num) != ind:
return [ind, nums.index(target-num)]
return -1

直接利用了列表的索引。

运行速度仅为4ms

但是其中肯定用到了其他遍历比如nums.index(target-num)。这就是Python最大的优势吧。简单,容易理解。

3、C语言解法

说实话,我还没系统的学过C++呢。专业不是这类的,学校不给我们安排课。这次先用C。等我慢慢学学C++再用C++

我的解法:

 #include<stdio.h>

 /**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i,j;
static int result[];
for(i=;i<numsSize-;i++)
{
for(j=i+;j<numsSize;j++)
{
if(*(nums+i)+*(nums+j)==target)
{
*result = i;
*(result+)=j;
}
}
}
return(result);
}
int main()
{
int nums[]={,,,};
int target = ;
int numSize=;
int *result;
result=twoSum(nums,numSize,target);
printf("succeed\n");
for(int i=;i<;i++)
{
printf("%d\n",*(result+i));
} return ;
}

只是简单的遍历。丝毫没有新意

大神解法:

 /**
* Note: The returned array must be malloced, assume caller calls free().
*/ int* twoSum(int* nums, int numsSize, int target) {
int i, max, min;
max = min = nums[];
for(i = ; i < numsSize; i++) {
if(nums[i] > max) max = nums[i];
if(nums[i] < min) min = nums[i];
} int *map = (int*)calloc((max-min+), sizeof(int));
int *reval = (int*)malloc(sizeof(int)*); for(i = ; i < numsSize; map[nums[i]-min] = ++i) {
int lookfornum = target - nums[i];
if(lookfornum < min || lookfornum > max) continue;
int dis = lookfornum - min;
if (map[dis]) {
reval[] = i;
reval[] = map[dis] -;
break;
}
} return reval; }

这个是所有解法里运行的最快的了。引用了我根本没听说过的map。我也很无奈呀。还要注意内存的申请呀。不过我好像没看到free

今天比较晚了。我还想再画画程序流程图的,既然做了,就要做透。

LeetCode——Problem1:two sum的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. LeetCode one Two Sum

    LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...

  9. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

随机推荐

  1. JavaScript模块化开发的那些事

    模块化开发在编程开发中是一个非常重要的概念,一个优秀的模块化项目的后期维护成本可以大大降低.本文主要介绍了JavaScript模块化开发的那些事,文中通过一个小故事比较直观地阐述了模块化开发的过程. ...

  2. python_32_文件操作1

    #目录里先创建一个yesterday文件 '''对文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 ''' print(open('yesterday',enc ...

  3. pyqt4 python2.7 中文乱码的解决方法

    import sysimport localefrom PyQt4.QtGui import *from PyQt4.QtCore import *from untitled import Ui_Di ...

  4. 转:Python字典与集合操作总结

    转自:http://blog.csdn.net/business122/article/details/7537014 一.创建字典 方法①: >>> dict1 = {} > ...

  5. Oracle 事务 锁

    一. 事务 是一系列的数据库操作,是数据库应用的基本逻辑单位以及并发控制的基本单位.所谓的事务,它是一个操作序列,这些操作要么都执行,要么都不执行,它是一个不可分割的工作单位. 要将有组语句作为事务考 ...

  6. MySQL DBA从小白到大神实战

    MySQL5.6 For CentOS 6.6 源码编译安装 o1.关闭防火墙o2.配置sysctl.confo3.检查操作系统上是否安装了MySQLo4.下载mysql源码包o5.添加用户和组o6. ...

  7. C++ 无限定名称查找

    无限定名称查找 (关键字:懒惰,挑捡,using指令的特殊性) 无限定名称查找实际上就是指没有限定(名称空间和名称空间运算符)名存在的一个名字的出现,其中对于using指令,其内部包含的所有的声明是被 ...

  8. SAP增强Enhancement

    第一代:基于源码增强(子过程subroutine) 第一代增强基于源代码,是SAP提供的一个空代码的子过程.在这个子过程中用户可以添加自己的代码,控制自己的需求.这类增强集中在一些文件名倒数第二个字符 ...

  9. 谈谈Integer中的静态类IntegerCache

            学习的本质就是一个赋值的过程,用新知识来覆盖你的旧知识或者无知(null).掌握知识是自己的, 分享知识,才能帮助更多的人,创造更大的价值.学贵以恒,以此自勉,与君共享.----曦阳X ...

  10. 16.2--Jenkins+Maven+Gitlab+Tomcat 自动化构建打包、部署

    分类: Linux服务篇,Linux架构篇   一.环境需求 本帖针对的是Linux环境,Windows或其他系统也可借鉴.具体只讲述Jenkins配置以及整个流程的实现. 1.JDK(或JRE)及J ...