LeetCode解题记录(1)
2015-04-09 20:38
267 查看
LeetCode解题记录(1)
目录
LeetCode解题记录1目录
前言
正文
题目
解法一
解法二
解法三
前言
我将慢慢开始做LeetCode上的题,并做解题记录发布在这里。我每题会给出一到多个解法,记录思考过程。我算法巨烂,是想通过这种方式稍微补补,基本功和我一样差的小伙伴可以和我一起共勉,有大神路过可以指点一二,我感激不尽。解题的最底要求是能通过LeetCode的检测,我不会丧病的为了各种提高效率在一个题上纠缠不休,所以最终解法可能也不怎么样,大家看看就好~编程语言一律采用C#。题解代码会按编号发布到我的GitHub上(仅保留最终解法)。正文
题目
problem001:Given an array of integers, find two numbers such that they add up to
a specific target number.
The function twoSum should return indices of the two numbers such that
they add up to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are
not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
解法一
最先想到的是普通的双循环遍历:public class Solution { public Tuple<int, int> TwoSum(int[] numbers, int target) { int count = numbers.Length; for(int i = 0;i < count;++i){ for(int j = i+1;j < count;++j){ if((numbers[i]+numbers[j])==target){ Tuple<int,int> result = new Tuple<int,int>(i+1,j+1); return result; } } } return null; } }
超时了,没通过!
解法二
然后咱们来用库函数:public class Solution { public Tuple<int, int> TwoSum(int[] numbers, int target) { int count = numbers.Length; for(int i = 0;i < count;++i){ int sub = target - numbers[i]; int j = Array.IndexOf(numbers,sub,i+1); if(j != -1){ return new Tuple<int,int>(i+1,j+1); } } return null; } }
超时啦,没通过!
解法三
看了下Discuss大家的解法,然后用C#实现了下:public class Solution { public Tuple<int, int> TwoSum(int[] numbers, int target) { //复用数组长度 int count = numbers.Length; //使用字典记录数组的值与target的差和索引 Dictionary<int,int> myDictionary=new Dictionary<int,int>(); for(int i = 0;i < count;++i){ if(!myDictionary.ContainsKey(numbers[i])){ //Dictionary不能插入重复键 if(!myDictionary.ContainsKey(target-numbers[i])) myDictionary.Add(target-numbers[i],i+1); }else{ return new Tuple<int,int>(myDictionary[numbers[i]],i+1); } } return null; } }
终于过了,85ms。
相关文章推荐
- [leetcode] database解题记录
- 2015.03.28 leetcode LRU cache 解题记录
- leetcode小白解题记录——第六题
- leetcode小白解题记录——第十一题
- leetcode小白解题记录——第十题
- [LeetCode]Valid Sudoku解题记录
- Leetcode Database 18道题解题记录
- leetcode小白解题记录——第五题
- Leetcode解题记录
- LeetCode 318. Maximum Product of Word Lengths解题记录
- 2015.03.30 LeetCode Merge Intervals 解题记录
- LeetCode解题记录(6)
- LeetCode解题记录(5)
- LeetCode 31 Next Permutation 解题记录
- leetcode小白解题记录——第二题
- [leetcode解题记录]Jump Game和Jump Game II
- LeetCode解题记录(4)
- LeetCode解题记录(8)
- leetcode小白解题记录——第九题
- [LeetCode]Valid Sudoku解题记录