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

题目描述:

给定一个数组,一个数字(Target),寻找数组中两个数字a和b,使得a+b=Target,打印a和b的下标。

题解:

第一反应是如果直接遍历O(N^2)暴力求解肯定TLE,果不其然。

第二反应是用二分查找,O(N*logN)的复杂度应该可以AC,但是我想到一个更简洁的方法,二分就没有测试。

解决方法:

使用HaspMap,遍历numbers数组,将target-numbers[i]放入map,对应的value是i,循环遍历,当发现当前数组元素已经存在于map中,说明和前面的某个元素加起来正好等于target;这时取出map中numbers[i]的value值+1作为第一个数的下标,数组下标i+1作为第二个数的下标。

public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
int key = numbers[i];
if (map.containsKey(key)) {//如果map中存在,说明找到了
res[0] = map.get(key) + 1;
res[1] = i + 1;
break;
} else {
map.put(target - key, i);//遍历numbers数组,将target-key放入map
}
}
return res;
}

LeetCode——Two Sum的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  6. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  8. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  9. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  10. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. 如何解决eclipse上的Android程序“Please ensure that adb is correctly located at 'D:\eclipse\sdk\platform-tools\adb.exe' and can be executed.”小问题?

    首先,把运行的Android模拟器和eclipse一块儿关了, 然后win+R,cmd, 下面输入adb kill_server 再输入adb start_server 之后重新运行项目,不出意外的话 ...

  2. ARM map(Program size)

    1.Keil程式编译完之后,在List目录下会生成一个.map文件,里面包含各个存储块数据大小. Code:ARM 指令. RO(Read only)只读数据,如const int gu8test = ...

  3. uva 1391 Astronauts(2-SAT)

    /*翻译好题意 n个变量 不超过m*2句话*/ #include<iostream> #include<cstdio> #include<cstring> #inc ...

  4. C#反射—解决类的实例化问题

    利用简单工厂模式来改进抽象工厂使用的复杂性(抽象工厂详见 设计模式之—抽象工厂模式) 数据表(User)业务处理接口(IUser) namespace FactoryMethodPatternDB.C ...

  5. J2EE初探

    J2EE概述 3层结构 4层模型 13项核心技术 J2EE容器 J2EE的优势与缺陷   J2EE概述 Java 2平台有3个版本,分别是适用于小型设备和智能卡的Java 2平台Micro版(Java ...

  6. jquery val() and text().

    .val() works on input elements (or any element with a value attribute?) and .text() will not work on ...

  7. aborb()程序结束形式

    abort()与exit()的区别?         分类:             MFC              2011-01-04 14:13     2233人阅读     评论(0)   ...

  8. 用core dump来调试程序段错误

    有的程序可以通过编译, 但在运行时会出现Segment fault(段错误). 这通常都是指针错误引起的.但这不像编译错误一样会提示到文件->行, 而是没有任何信息, 使得我们的调试变得困难起来 ...

  9. Android放大镜的实现

    package chroya.demo.magnifier; import android.content.Context; import android.graphics.Bitmap; impor ...

  10. Android学习----Activity

    一.什么是activity Activity 是用户接口程序,原则上它会提供给用户一个交互式的接口功能.它是 android 应用程序的基本功能单元.Activity 本身是没有界面的.所以activ ...