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. Linux如何关闭防火墙和查看防火墙的具体情况

    1.Linux下关闭和开启防火墙 1) 重启后生效 开启: chkconfig iptables on 关闭: chkconfig iptables off 2) 即时生效,重启后失效 开启: ser ...

  2. sizeof操作符-结构体与类大小

    导读 sizeof是C/C++一个难点,当在自定义类上应用sizeof操作符时,总会出现意想不到的结果,下面,我们就来探讨一下sizeof这个操作符! 目录 1. sizeof与strlen的区别 2 ...

  3. redis 自启动脚本

    看到网上许多手写的亦或复制的redis开机自启动脚本, 版本好多, 其实最简单的可以从下载的redis文件里找得到 我下载的redis是 3.0.3 版本的,  对于其他版本, 没有详细查看, 有需要 ...

  4. Python开发【第十三篇】:jQuery--无内容点击-不进去(一)

    Python开发[第十三篇]:jQuery--无内容点击-不进去(一)

  5. AJAX入门学习(转)

    一.基础概念 1.全称:Asynchronous.JavaScript.And.XML(异步的 JavaScript 和 XML). 2.定义: Ajax不是一个技术,它实际上是几种技术,每种技术都有 ...

  6. 动态的显示当前的时间---setInterval的用法

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. iOS开发之四张图说明GCD(Grand Central Dispatch)附Test源码

    首先,先介绍几个概念:GCD,队列,串行,并行,同步,异步.                                                                       ...

  8. iOS面试小题集锦

      1.Object-C有多继承吗?没有的话用什么代替? cocoa 中所有的类都是NSObject 的子类 多继承在这里是用protocol 委托代理 来实现的你不用去考虑繁琐的多继承 ,虚基类的概 ...

  9. 基于Jquery easyui 选中特定的tab并更新

    获取选中的 Tab // 获取选中的 tab panel 和它的 tab 对象 var pp = $('#tt').tabs('getSelected'); var tab = pp.panel('o ...

  10. Android获取屏幕的高度和宽度

    方法一: DisplayMetrics metrics=new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics( ...