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: input: nums = [2, 7, 11, 15] , target=9.

output:  [0, 1]

给定一个整型数组与一个目标数,输出两个数相加为此目标数的下标。(只有一个结果,且每个数只能使用一次)

1. 最简单的方法就是双重循环,取到之后return. 不过太耗时了,肯定不符合要求。

所以我在每次循环里面,查找数组有没有另一个值。(做算法题的话应该不能使用.ToList()这样的方法吧?)

public int[] TwoSum(int[] nums, int target) {
for(int index = ; index < nums.Length; index++){
int element = nums[index];
int otherElement = target - element;//查找是否存在
int otherIndex = nums.ToList().IndexOf(otherElement);//主要是这一步
if(otherIndex != - && otherIndex != index){
return new int[]{index,otherIndex};
}
}
return null;
}

耗时:652ms.  内存:48.7MB

2. 在上面的基础上从把数组转换成字典,从其中查找,查找速度应该比数组快。

 public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> dic = new Dictionary<int, int>();
for(int index = ; index < nums.Length; index++){
dic[index] = nums[index];
}
for(int index = ; index < nums.Length; index++){
int element = nums[index];
int otherElement = target - element;//查找是否存在
bool containsValue = dic.ContainsValue(otherElement);//主要是这一步
if(containsValue){
int foundKey = -;
foreach (int key in dic.Keys){
if (dic[key] == otherElement && key != index){
foundKey = key;
return new int[]{index, foundKey};
}
}
}
}
return null;
}

耗时:788 ms.  内存:29.6 MB  不过找到元素后还得取出下标,又是一个循环。不过内存占用变小了。

3. 只需要一个循环。 每次查找当前元素的匹配项前,把前一个数放入字典中,从字典查找匹配项。如果匹配到了,则当前index为后一个数的下标。

 public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> dic = new Dictionary<int, int>();
for(int index = ; index < nums.Length; index++){
if(dic.ContainsKey(target - nums[index]))
return new int[]{dic[target - nums[index]],index};
dic[nums[index]] = index;
}
  return null;
}

252 ms. 29.4 MB。题目中说结果只有一个,所以就算是数组元素作为key也没事。而且通过key容易找出value下标值。

但是如果会有多个重复值,上述就不适用了,给同一个key赋值,value会被覆盖掉。

例如 input:[5,5,8,3]  target=13。 本应该输入[0, 2], 可是上述结果却输出了[1, 2].

因此需要使用下标作为key才行. 不过此时通过value快捷查找key又成了问题。看看以后会不会有这类题目。

1. Two Sum [Array] [Easy]的更多相关文章

  1. 1. Two Sum【easy】

    1. Two Sum[easy] Given an array of integers, return indices of the two numbers such that they add up ...

  2. [array] leetCode-26. Remove Duplicates from Sorted Array - Easy

    26. Remove Duplicates from Sorted Array - Easy descrition Given a sorted array, remove the duplicate ...

  3. LeetCode--Sort Array By Parity && N-Repeated Element in Size 2N Array (Easy)

    905. Sort Array By Parity (Easy)# Given an array A of non-negative integers, return an array consist ...

  4. LeetCode Array Easy 167. Two Sum II - Input array is sorted

    Description Given an array of integers that is already sorted in ascending order, find two numbers s ...

  5. LeetCode Array Easy 1. Two Sum

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  6. Group and sum array of hashes by date

    I have an array of hashes like this: [{:created=>Fri, 22 Jan 2014 13:02:13 UTC +00:00, :amount=&g ...

  7. LeetCode--219、268、283、414、448 Array(Easy)

    219. Contains Duplicate II Given an array of integers and an integer k, find out whether there are t ...

  8. LeetCode--122、167、169、189、217 Array(Easy)

    122. Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price ...

  9. LeetCode--1、26、27、35、53 Array(Easy)

      1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to ...

随机推荐

  1. MongoDB 数据查询

    数据查询 基本查询 方法find():查询 db.集合名称.find({条件文档}) 方法findOne():查询,只返回第一个 db.集合名称.findOne({条件文档}) 方法pretty(): ...

  2. conductor 系统任务

    动态任务: 参数: dynamicTaskNameParam:来自任务输入的参数的名称,其值用于调度任务. 例如 如果参数的值为ABC,则调度的下一个任务类型为“ABC”. Example { &qu ...

  3. redis的五种常见数据类型的常用指令

      一.String字符串,key-value 应用场景:string是redis的最基本数据类型,key-value格式,一个key对应一个值的情况下 1.设置key = value:set key ...

  4. 代理URI和服务器URI的不同

    [代理URI和服务器URI的不同] 1.向Web服务器直接发送请求时,路径为相对路径(不包含域名). 2.当向代理发送请求时,路径为绝对路径(包含域名). 参考<HTTP权威指南>6.5. ...

  5. SweetAlert2 弹窗

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  6. javascript的数据检测总结

    目录 javaScript的数据检测 1.typeof 2.instanceof 3.constructor 4.Object.prototype.toString.call()--------- 一 ...

  7. spring框架中工厂方法的创建和销毁

    1.编写接口UserSerivce: public interface UserService { public void sayHello(); } 2.编写实实现接口的方法,在该方法中除了要实现接 ...

  8. Windows 7 手动添加受信任证书教程

    步骤如下: 1.点击开始-运行,如下图: 2.弹出"控制台"窗口如下,如下图: 3.点击"文件-添加/删除管理单元",如下图: 4.选择"证书&quo ...

  9. chrome 调试工具的使用

    Elements chrome devtools 中 Elements panel 是审查 dom 元素和 css 的, 可以实时修改 dom/css. windows: ctrl + shift + ...

  10. 【附源文件】日记类App原型制作分享-Grid Diary

    Grid Diary是一款非常受文艺青年喜爱的记录应用,它设计简单,内容却非常丰富.它不再是单调的文字记录,界面的设计非常与众不同,由许多格子拼凑而成,每一个格子里面还带有一个问题,十分有趣.提到格子 ...