LeetCode初体验—twoSum
今天注册了大名鼎鼎的LeetCode,做了一道最简单的算法题目:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
虽然题目很简单,但是在做的过程中暴露的问题也是比较多的。
1.多年不碰英语,题目看不懂,很多细节没有理解(例如给定的序列中的数字是不是可以重复、以及序列的长度等)
2.由于没有做过类似的网上直接运行提交的题目,所以一时间不会搞
3.用惯了VS的只能提示,导致直接写代码的时候字母的大小写经常错误
4.可能导致程序崩溃的条件不加,例如这个题目,明显在输入的数组的长度小于2时候可以直接返回
我的程序:
public class Solution {
public int[] TwoSum(int[] nums, int target) {
];
)
{
return temp;
}
;i<=nums.Length - ;i++){
;j<=nums.Length - ;j++){
if((nums[i] + nums[j] == target)){
temp[] = i;
temp[] = j;
return temp;
}
}
}
return temp;
}
}
做完提交后会有一个性能分析和排名:

通过上面可以看到我的计算方法的效率,说明有60%多的算法比我这个效率要高,所以可以看看人家是怎么做的:
查看算法的讲解,有一种方法是采用了哈希表的方式,我上面的方式采用的是暴力搜索的方式,时间复杂度O(n2),而采用哈希的方式是O(n)
Approach #2 (Two-pass Hash Table) [Accepted]
To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.
We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in nearconstant time. I say "near" because if a collision occurred, a look up could degenerate to O(n)O(n) time. But look up in hash table should be amortized O(1)O(1) time as long as the hash function was chosen carefully.
A simple implementation uses two iterations. In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
Complexity Analysis:
Time complexity : O(n)O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduces the look up time to O(1)O(1), the time complexity is O(n)O(n).
Space complexity : O(n)O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly nn elements.
思路有了,用C#去改写
public int[] TwoSum(int[] nums, int target)
{
if (nums.Length < 2)
{
throw new Exception();
}
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i <= nums.Length - 1; i++)
{
dict.Add(i, nums[i]);
}
for (int i = 0; i <= nums.Length - 1; i++)
{
int temp = target - nums[i];
if (dict.ContainsValue(temp) && dict.FirstOrDefault(q => q.Value == temp).Key != i)
{
return new int[] { dict.FirstOrDefault(q => q.Value == temp).Key, i };
}
}
throw new Exception();
}
但是在提交的时候出现了问题:
超时了!!!!
和大神们讨论了一下也没发现什么问题。
还有一种是这个变种:
Approach #3 (One-pass Hash Table) [Accepted]
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
就是把上面的两次循环,变成了一次循环,把先构建哈希表变成了后构建,每次循环时候去看是否存在。
偶然发现有人这么写的,于是就扒下来看了一下:
public int[] TwoSum(int[] nums, int target)
{
int numsLength = nums.Length;
)
{
return nums;
}
];
var numsInDictionary = new Dictionary<int, int>();
; i < numsLength; i++)
{
if (numsInDictionary.ContainsKey(target - nums[i]))
{
result[] = i;
result[] = numsInDictionary[target - nums[i]];
break;
}
if (!numsInDictionary.ContainsKey(nums[i]))
{
numsInDictionary.Add(nums[i], i);
}
}
return result;
}

LeetCode初体验—twoSum的更多相关文章
- [leetcode]leetcode初体验
这几天把之前的设计模式回顾了一遍,整理了一点以前的项目.同学说,打算刷leetcode题目,也勾起了我的兴趣,索性也刷一些题目,再提高一些内功.刚开始进去,leetcode随机分配的题目,直接也就做了 ...
- .NET平台开源项目速览(15)文档数据库RavenDB-介绍与初体验
不知不觉,“.NET平台开源项目速览“系列文章已经15篇了,每一篇都非常受欢迎,可能技术水平不高,但足够入门了.虽然工作很忙,但还是会抽空把自己知道的,已经平时遇到的好的开源项目分享出来.今天就给大家 ...
- Xamarin+Prism开发详解四:简单Mac OS 虚拟机安装方法与Visual Studio for Mac 初体验
Mac OS 虚拟机安装方法 最近把自己的电脑升级了一下SSD固态硬盘,总算是有容量安装Mac 虚拟机了!经过心碎的安装探索,尝试了国内外的各种安装方法,最后在youtube上找到了一个好方法. 简单 ...
- Spring之初体验
Spring之初体验 Spring是一个轻量级的Java Web开发框架,以IoC(Inverse of Control 控制反转)和 ...
- Xamarin.iOS开发初体验
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKwAAAA+CAIAAAA5/WfHAAAJrklEQVR4nO2c/VdTRxrH+wfdU84pW0
- 【腾讯Bugly干货分享】基于 Webpack & Vue & Vue-Router 的 SPA 初体验
本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57d13a57132ff21c38110186 导语 最近这几年的前端圈子,由于 ...
- 【Knockout.js 学习体验之旅】(1)ko初体验
前言 什么,你现在还在看knockout.js?这货都已经落后主流一千年了!赶紧去学Angular.React啊,再不赶紧的话,他们也要变out了哦.身旁的90后小伙伴,嘴里还塞着山东的狗不理大蒜包, ...
- 在同一个硬盘上安装多个 Linux 发行版及 Fedora 21 、Fedora 22 初体验
在同一个硬盘上安装多个 Linux 发行版 以前对多个 Linux 发行版的折腾主要是在虚拟机上完成.我的桌面电脑性能比较强大,玩玩虚拟机没啥问题,但是笔记本电脑就不行了.要在我的笔记本电脑上折腾多个 ...
- 百度EChart3初体验
由于项目需要在首页搞一个订单数量的走势图,经过多方查找,体验,感觉ECharts不错,封装的很细,我们只需要看自己需要那种类型的图表,搞定好自己的json数据就OK.至于说如何体现出来,官网的教程很详 ...
随机推荐
- jqgrid在页面出来竖型滚动条自动调整列宽
在项目中使用jqgrid的时候,需要设置在页面竖型滚动条出来的时候,列宽进行调整 1. 判断jqgrid的宽度是否和页面的宽度不一致(判断滚动条是否出来) 2. 调整jqgrid的列宽,因为jqgri ...
- android获取根视图
android获取根视图 activity.getWindow().getDecorView()
- Struts2中的session、request、respsonse获取方法
个人对于struts有一种复杂的心情,平心而论,struts2是个人最早接触到的的框架,在学校的时候就已经开始学习了,大四毕业设计,无疑用的还是struct,那时候SSH还是很流行的,后来出来实习,直 ...
- cocos2d-x Animation
转自:http://codingnow.cn/cocos2d-x/810.html 这一篇来学习怎么使用cocos2d-x引擎播放帧动画,就是把一帧一帧的图片像电影那样显示出来.1. 首先来了解一下相 ...
- [C语言(VC)] 打造自己的键盘记录器 (zaroty)
说起键盘记录,想必很多朋友都用过网上流传的一些键盘记录软件吧,但是有没有想过自己写一个呢?也许你会想:会不会很复杂啊?我可以很负责的告诉你,写键盘记录是很简单的.你所需要的仅仅是懂得一些C语言的DLL ...
- 【转】简明vim练级攻略
本文来自:http://coolshell.cn/articles/5426.html vim的学习曲线相当的大(参看各种文本编辑器的学习曲线),所以,如果你一开始看到的是一大堆VIM的命令分类,你一 ...
- 【54】让自己熟悉包括TR1在内的标准程序库
1.C++0X,不确定哪一年出来,意指200X版的C++ 2.C++标准程序库的主要机能有:STL,iostreams,locals等. 3.TR1:Technical Report 1,只是一份规范 ...
- js 如何把JSON格式的字符串转换为JSON对象
直接用eval函数.例:var str1 = '{ "url": "www.51qdq.com", "name": "js&quo ...
- poj 1904 King's Quest tarjan求二分图的所有可选最大匹配边
因为是完美匹配,所以每个点都已经匹配了,那么如果要选择一条别的边,增光路的最后必定找到原来所匹配的点,加上匹配的边,那么就是一个环.所以可选边在一个强连通分量里. #include <iostr ...
- paip.输入法编程---词频顺序order by py
paip.输入法编程---词频顺序order by py 作者Attilax , EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn ...