您的位置:首页 > 其它

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: