早就想刷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. mustache.js 数组循环的索引

    在使用mustache作为模板引擎时,想要利用数组中的对象的索引排序,却发现mustache中无法获得数组索引,在一番搜索之后,发现在数组的对象中加入索引,就可以了,示例如下 /html {{#dat ...

  2. codeforces 600C Make Palindrome

    要保证变化次数最少就是出现次数为奇数的相互转化,而且对应字母只改变一次.保证字典序小就是字典序大的字母变成字典序小的字母. 长度n为偶数时候,次数为奇数的有偶数个,按照上面说的搞就好了. n为奇数时, ...

  3. 【洛谷3950】部落冲突(LCT维护连通性)

    点此看题面 大致题意: 给你一棵树,\(3\)种操作:连一条边,删一条边,询问两点是否联通. \(LCT\)维护连通性 有一道类似的题目:[BZOJ2049][SDOI2008] Cave 洞穴勘测. ...

  4. Problem J: 搜索基础之红与黑

    Problem J: 搜索基础之红与黑 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 170  Solved: 100[Submit][Status][ ...

  5. Hadoop完全分布式集群环境搭建

    1. 在Apache官网下载Hadoop 下载地址:http://hadoop.apache.org/releases.html 选择对应版本的二进制文件进行下载 2.解压配置 以hadoop-2.6 ...

  6. javaweb基础(25)_jsp标签实例一

    一.简单标签(SimpleTag) 由于传统标签使用三个标签接口来完成不同的功能,显得过于繁琐,不利于标签技术的推广, SUN公司为降低标签技术的学习难度,在JSP 2.0中定义了一个更为简单.便于编 ...

  7. python 读取mat文件

    import osimport scipy.io as sio import numpy as np #matlab文件名 matfn='/home/user/devkit/data/meta_det ...

  8. windows下安装win7虚拟机并安装oracle

    一.win7虚拟机 与安装linux虚拟机没有什么不同,不同的是选择客户机操作系统.内存.磁盘容量,以及映像文件. 创建win7虚拟机步骤简化: 新建虚拟机-->>自定义-->> ...

  9. Ubuntu解决winscp连接不上虚拟机问题

    前几天在配置虚拟机的时候,尝试用winscp连接Ubuntu,结果连接被拒绝.原因:Ubuntu的ssh服务需要自己安装和启动,在没启动之前,是无法连接上去的 解决方案: 我们可以输入:ssh loc ...

  10. Linux MySQL 8.0 忘记密码

    不小忘了MySQL的密码,按照书上和网上的内容都没能修改成功,终于在借鉴了多篇文章成功之后找到原因,修改密码成功 修改 MySQL 密码 第一步:关闭 MySQL 进程 systemctl stop ...