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

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

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 int[] twoSum(int[] numbers, int target) {        int[] result = new int[2];		int length = numbers.length;		Map
difference = new HashMap
(); for(int i = 0; i < length; ++i) difference.put(target - numbers[i], i); for(int i = 0; i < length; ++i){ if(difference.containsKey(numbers[i]) && i != difference.get(numbers[i])){ result[0] = Math.min(i, difference.get(numbers[i])) + 1; result[1] = Math.max(i, difference.get(numbers[i])) + 1; break; } } return result; }}

  

转载于:https://www.cnblogs.com/averillzheng/p/3769075.html

你可能感兴趣的文章
TLS/SSL
查看>>
zoj2319Beautiful People Dp
查看>>
图片加载 背景色块问题
查看>>
Static Binding (Early Binding) vs Dynamic Binding (Late Binding)
查看>>
搭建git服务器
查看>>
iOS之UIDynamic UI动力学使用步骤
查看>>
poj 2498 动态规划
查看>>
Windows Phone 7中使用PhoneApplicationService类保存应用程序状态
查看>>
MySql数据库的下载和安装卸载
查看>>
JDBC接口核心的API
查看>>
双缓冲技术局部更新原理之派生自View
查看>>
PPAPI插件与浏览器的通信
查看>>
用 query 方法 获得xml 节点的值
查看>>
Hello,Android
查看>>
Sublime Text 3 build 3103 注册码
查看>>
删与改
查看>>
SAP 中如何寻找增强
查看>>
spi驱动无法建立spidev问题
查看>>
ANDROID开发之SQLite详解
查看>>
如何依靠代码提高网络性能
查看>>