博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 1 Two Sum
阅读量:7062 次
发布时间:2019-06-28

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

翻译:

给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数twoSum返回这两个相加起来等于目标值的数字的索引,且index1必须小于index2。请记住你返回的答案(包括index1和index2)都不是从0开始的。你可以假定每个输入都有且仅有一个解决方案。输入: numbers={2, 7, 11, 15}, target=9输出: index1=1, index2=2

原文:

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=9Output: index1=1, index2=2

C++

class Solution {public:    vector
twoSum(vector
& nums, int target) { map
mapping; vector
result; for (int i = 0; i < nums.size(); i++) { mapping[nums[i]] = i; } for (int i = 0; i < nums.size(); i++) { int searched = target - nums[i]; if (mapping.find(searched) != mapping.end() && mapping.at(searched) != i) { result.push_back(i + 1); result.push_back(mapping[searched] + 1); break; } } return result; }};

Java

public class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap
map=new HashMap
(); int[] result=new int[2]; for(int i=0;i

C#(超时)

public static int[] TwoSum(int[] nums, int target){    Dictionary
map = new Dictionary
(); int[] result = new int[2]; for (int i = 0; i < nums.Length; i++) { map.Add(i, nums[i]); } for (int i = 0; i < nums.Length; i++) { if (nums[i] > target) continue; int searched = target - nums[i]; if (map.ContainsValue(searched)) { int index = map.Where(x => x.Value == searched).Select(x => x.Key).FirstOrDefault(); if (index != i) { if (index < i) { result[0] = index + 1; result[1] = i + 1; } else { result[0] = i + 1; result[1] = index + 1; } } } } return result;}

转载地址:http://wnbll.baihongyu.com/

你可能感兴趣的文章
学生登录管理系统
查看>>
Linux的浏览器中等宽字体显示不正常的问题
查看>>
【Ansible】 Playbook 中的变量和引用
查看>>
仓库常需要对货品和数据记录
查看>>
使用c++实现乘法表输出
查看>>
100个常用的linux命令
查看>>
我的友情链接
查看>>
每天laravel-20160817| Container -20
查看>>
通用权限管理框架
查看>>
我的友情链接
查看>>
申请SSL证书怎样验证域名所有权
查看>>
Java开发在线打开编辑保存Word文件
查看>>
将学习进行到底!为普通人的奋斗送福
查看>>
常用十大python机器学习库
查看>>
TCP/IP三次握手四次挥手
查看>>
Systemstate Dump分析经典案例(下)
查看>>
PHPcms怎么调用二级栏目
查看>>
中小型网络构建案例——防火墙的应用
查看>>
《Linux就该这么学》 第3章 管道符、重定向与环境变量
查看>>
Okhttp3使用
查看>>