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

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

Two Sum

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

Java代码:

public class Solution {    public int[] twoSum(int[] numbers, int target) {        HashMap
map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { if (target == numbers[i] * 2) { int[] result = new int[2]; result[0] = map.get(numbers[i]); result[1] = i + 1; return result; } } else map.put(numbers[i], i + 1); } int tmp = 0; for (int i = 0; i < numbers.length; i++) { tmp = target - numbers[i]; if (map.containsKey(tmp)) { int[] result = new int[2]; result[0] = map.get(numbers[i]); result[1] = map.get(tmp); if (result[0] == result[1]) continue; else return result; } } return null; }}

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

你可能感兴趣的文章
图文详解Unity3D中Material的Tiling和Offset是怎么回事
查看>>
voxel 与 pixel
查看>>
vector3.forward和transform.forward的区别!
查看>>
HOLOLENS的空间管理
查看>>
unity3d 的Quaternion.identity和transform.rotation区别是什么
查看>>
【Unity3d】Ray射线初探-射线的原理及用法
查看>>
迄今最深入、最专业的Hololens评测结果,美国AR大咖艾迪·奥夫曼现身说法
查看>>
全息眼镜HoloLens可快速捕捉真人3D图像
查看>>
copy-paste component
查看>>
【Unity】矩阵运算
查看>>
理解向量运算
查看>>
正弦 sin 余弦 cos
查看>>
微积分
查看>>
Vector3 *2 ,ToString()自动四舍五入
查看>>
2016年秋季的我,work with hololens
查看>>
叉积与点积
查看>>
λ怎么 读
查看>>
Rect 和 Bounds
查看>>
HOLOLENS不适合加天空盒
查看>>
Unity UI on hololens
查看>>