LeetCode——Problem1:two sum
早就想刷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)
其中遇到了一个错误
这个因为之前我后面几行的代码是
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的更多相关文章
- 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 ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [leetCode][013] Two Sum 2
题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
- LeetCode one Two Sum
LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...
- [leetcode]40. Combination Sum II组合之和之二
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
随机推荐
- 又一例网卡mtu值引发的问题
通过php上传文件到云存储,很小的文件都无法上传,在别的服务器上测试可以,本机环境是ESXI虚机安装的centos 7版本 解决思路过程 1.让开发写一个单独测试上传的文件,不调php nginx配置 ...
- python资料汇总
http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html
- java设计模式、框架、架构、平台之间的关系
设计模式<框架<架构<平台,从复用角度讲,设计模式是代码级复用.框架是模块级复用.架构是系统级复用.平台是企业应用级复用. 1.设计模式 为什么要先说设计模式?因为设计模式在 ...
- Android(java)学习笔记98:如何让你的GridView不再滚动
1. 如何让你的GridView不再滚动: GridView显示不完整的原因是因为,他的外层也套用了一个滑动的控件,这个解决办法是:重写GridView,是控制GridView不能滚动,就是写一个类继 ...
- 【洛谷2051】[AHOI2009] 中国象棋(烦人的动态规划)
点此看题面 大致题意: 让你在一张\(N*M\)的棋盘上摆放炮,使其无法互相攻击,问有多少种摆法. 辟谣 听某大佬说这是一道状压\(DP\)题,于是兴冲冲地去做,看完数据范围彻底懵了:\(N≤100\ ...
- mac 扫描存活IP段
法一:脚本内容 MacdeMacBook-Pro:~ root# cat ping-ttl.sh #!/bin/bash [ $UID -ne 0 ]&&{ echo "Pl ...
- 标准对象 -------JavaScript
本文摘要:http://www.liaoxuefeng.com/ 在JavaScript的世界里,一切都是对象. 但是某些对象还是和其他对象不太一样.为了区分对象的类型,我们用typeof操作符获取对 ...
- 从多个textarea中随机选取一个内容
<div id="IMContentTest"> <textarea name="IMContent" class="IMClass ...
- Smallest Common Multiple-freecodecamp算法题目
Smallest Common Multiple 1.要求 找出能被两个给定参数和它们之间的连续数字整除的最小公倍数. 2.思路 设定一个twoMultiple(a,b)函数,求出输入两个参数的最小公 ...
- 详解----memcache服务端与客户端
Memcache是danga.com的一个项目,用这个缓存项目来构建自己大负载的网站,来分担数据库的压力. 它可以应对任意多个连接,使用非阻塞的网络IO.由于它的工作机制是在内存中开辟一块空间,然后建 ...