博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1.找两个数下标Two Sum
阅读量:4319 次
发布时间:2019-06-06

本文共 799 字,大约阅读时间需要 2 分钟。

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].
用字典,存储当前值的下标,判断是否存在
target
-
nums
[
i
]
 
  1. public class Solution {
  2. public int[] TwoSum(int[] nums, int target) {
  3. if (nums == null || nums.Length < 1) {
  4. return null;
  5. }
  6. Dictionary<int, int> dict = new Dictionary<int, int>();
  7. for (int i = 0; i < nums.Length; i++) {
  8. if (dict.ContainsKey(target - nums[i])) {
  9. int[] arr = {
    dict[target - nums[i]], i};
  10. return arr;
  11. } else {
  12. dict[nums[i]] = i;
  13. }
  14. }
  15. return null;
  16. }
  17. }

转载于:https://www.cnblogs.com/xiejunzhao/p/fcf932b1763ef76888dded0cf4fee9d3.html

你可能感兴趣的文章
java开发操作系统内核:由实模式进入保护模式之32位寻址
查看>>
第五讲:单例模式
查看>>
Python编程语言的起源
查看>>
Azure ARMTemplate模板,VM扩展命令
查看>>
在腾讯云上创建您的SQL Cluster(4)
查看>>
linux ping命令
查看>>
Activiti源码浅析:Activiti的活动授权机制
查看>>
数位dp整理
查看>>
UNIX基础知识
查看>>
bzoj 1179: [Apio2009]Atm
查看>>
利用LDA进行文本聚类(hadoop, mahout)
查看>>
第三周作业
查看>>
js添加删除行
查看>>
浏览器性能测试网址
查看>>
[MTK FP]用Python把图片资源image.rar中为.pbm后缀的文件更改为.bmp后缀的方法
查看>>
实验二
查看>>
[LeetCode]203. Remove Linked List Elements 解题小结
查看>>
测试一下
查看>>
vue base64
查看>>
【Django实战开发】案例一:创建自己的blog站点-1.安装及搭建开发环境
查看>>