博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode算法题--刷题第一天
阅读量:4630 次
发布时间:2019-06-09

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

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]

 

 代码实现:(参考)

1     import java.util.HashMap;   2     import java.util.Map;   3        4     public class Solution {   5         public static int[] twoSum(int[] nums, int target) {   6             int[] result = new int[2];   7             Map
map = new HashMap(); 8 for(int i=0; i
i){ 11 result[0] = i; 12 result[1] = map.get(target - nums[i]); 13 }else{ 14 result[1] = i; 15 result[0] = map.get(target - nums[i]); 16 } 17 return result; 18 } 19 map.put(nums[i], i); 20 } 21 return result; 22 } 23 24 public static void main(String[] args) { 25 int[] nums = {3,2,4}; 26 int target = 6; 27 int[] result = new int[2]; 28 result = twoSum(nums,target); 29 System.out.println(result[0] + " " + result[1]); 30 } 31 }

 

 

 

转载于:https://www.cnblogs.com/dwystyle/p/8440083.html

你可能感兴趣的文章
NYOJ 366 D的小L
查看>>
PYTHON 写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者...
查看>>
Docker 初识
查看>>
【12.16】VC++调用Word OLE进行自动化生成报表
查看>>
用Maven创建第一个web项目
查看>>
php中的抽象类(abstract class)和接口(interface)
查看>>
linux安装ActiveMQ
查看>>
面向对象与软件工程---团队作业1
查看>>
认识一下Kotlin语言,Android平台的Swift
查看>>
hdu5389 Zero Escape
查看>>
【转】android电池(四):电池 电量计(MAX17040)驱动分析篇
查看>>
android中的回调
查看>>
redis启动、清缓存命令
查看>>
Java的Clone
查看>>
CSS 弹出层 支持IE/FF/OP
查看>>
maven的配置-2019-4-13
查看>>
进程调度
查看>>
百练 2973 Skew数 解题报告
查看>>
C# 温故而知新:Stream篇(二)
查看>>
回首2016,展望2017
查看>>