package org.lep.leetcode.twosum;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; /**
* source:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description
* Created by lverpeng on 2017/6/21.
*
* 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 TwoSum {
public static void main(String[] args) {
TwoSum twoSum = new TwoSum();
int[] numbers = {2, 7, 11, 15};
System.out.println(Arrays.toString(twoSum.twoSum(numbers, 9)));
System.out.println(Arrays.toString(twoSum.twoSumUseHash(numbers, 9)));
} /**
* 最简单的方法对于数组中每一个数,依次遍历其后每一个数字,直到找到两个和为target的数字
* 时间复杂度:O(n^2)
* 空间复杂度:O(1)
*
* @param numbers
* @param target
* @return
*/
public int[] twoSum (int[] numbers, int target) {
int[] result = new int[2];
for (int i = 0; i < numbers.length; i ++) {
for (int j = i; j < numbers.length; j++) {
if ((numbers[i] + numbers[j]) == target) {
result[0] = i + 1;
result[1] = j + 1;
return result;
}
}
}
return result;
} /**
* 由于上面第二次循环只是在查找一个数,那么就可以使用hash来查找,将第一个对应的另一个加数依次添加到hash表里,降低时间复杂度
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*
* @param numbers
* @param target
* @return
*/
public int[] twoSumUseHash (int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> needOtherNum = new HashMap<Integer, Integer>(); // <num, index>
for (int i = 0; i < numbers.length; i++) {
// 如果当前num是前面数字所需要的另外一个加数,说明找到了
if (needOtherNum.containsKey(numbers[i])) {
result[0] = needOtherNum.get(numbers[i]) + 1;
result[1] = i + 1;
break;
} else {
// 如果没有找到,则把当前数字所需要的另外一个加数添加到map中
needOtherNum.put(target - numbers[i], i);
}
}
return result;
}
}

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. C++入门

    <完美C++>第5版 (美)Walter Savitch,Kenrick Mock 萨维奇//默克 著  薛正华,沈庚,韦远科 译    出版社: 电子工业出版社 时间2019/4/11- ...

  2. idea编辑器激活码

    激活方式:License Server1.将地址 http://active.chinapyg.com/ 或者 http://idea.toocruel.net 任意一个复制到License Serv ...

  3. PowerShell工作流学习-6-向脚本工作流添加检查点

    关键点: a)检查点是工作流当前状态的快照,其中包括变量的当前值以及在该点生成的任何输出,这些信息保存在磁盘. b)检查点数据保存在托管工作流会话的计算机的硬盘上的用户配置文件中. c)当工作流通用参 ...

  4. pointer-events: none 的两个应用场景

    简介 pointer-events: none 真是个神奇的属性. 该属性有什么用?借用 CSS3 pointer-events:none 应用举例及扩展 的总结来说: pointer-events: ...

  5. android判断密码首字母大写正则表达式

    判断首字母大写"[A-Z]\\w+" \\w所有字符 \\d所有数字

  6. 哈夫曼(Huffman)树和哈夫曼编码

    一.哈夫曼(Huffman)树和哈夫曼编码 1.哈夫曼树(Huffman)又称最优二叉树,是一类带权路径长度最短的树, 常用于信息检测. 定义: 结点间的路径长度:树中一个结点到另一个结点之间分支数目 ...

  7. Linux-3.0.8中基于S5PV210的GPIO模块代码追踪和分析

    编写按键驱动时,想知道内核是如何管理GPIO的,所以开始追踪代码,中间走了一些弯路,现记录于此. 追踪代码之前,我猜测:第一,这部分代码应该在系统set up阶段执行:第二,GPIO的代码应该在mac ...

  8. 出错with root cause

    [背景:] 我自己写了一个项目,主页可以看到一个数据库里的一个应用的users用户表的所有数据,包括用户的年龄,姓名,出生日期等信息.后来又想再增加一个注册功能,写好了之后进行单元测试,结果就出现了w ...

  9. JAVA的 IO NIO AIO笔记

        IO      linux内核将所有外部设备都看做一个文件来操作,对一个文件的读写会调用内核系统命令,放回一个file descriptor(文件描述符), 对一个socket的读写也会有相应 ...

  10. Exp2 后门原理与实践-------20164325王晓蕊

    Exp2 后门原理与实践 任务一:使用netcat获取主机操作Shell,cron启动 1.windows获取linux shell 1.1 ipconfig  查看本机查看以太网适配器(8)的ipv ...