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. canvas绘制圆图输出图片格式

    function drawCircleImage(url, callback) { const canvas = document.createElement('canvas'); const img ...

  2. jsonp 简单封装

    import originJSONP from 'jsonp' // 引入 jsonp 模块 // 对外暴露方法 jsonp // 通常传给服务端的 url 地址带参数 设计目的是希望有纯净的 url ...

  3. 85、int 、NSInteger、NSUInteger、NSNumber的区别和联系

    NSNumber是NSValue的一个子类,它是一个对象来存储数字值包括bool型,它提供了一系列的方法来存储char a signed or unsigned char, short int, in ...

  4. centos7.6 ssh远程链接配置

    1.firewall增加22端口号 增加方式有两种,直接编辑firewall的public.xml增加 vi /etc/firewalld/zones/public.xml 进入后按i健光标移动到zo ...

  5. select、poll、epoll

    1.概念 select.poll.epoll都是事件触发机制,当等待的事件发生就触发进行处理,用于I/O复用 2.简单例子理解 3.select函数 3.1函数详解 int select(int ma ...

  6. 使用@Autowird注入报空指针异常

    new的对象不能调用此对象里面注入的其他类,如果想要调用注入的其他类,则此new的对象要使用@componet将此类注入. 原因:

  7. HTTP一、HTTP介绍与套接字

    目录 一.套接字 1.HTTP与Apache 2.应用层协议:HTTP 3.套接字(IP+协议端口的组合) 4.套接字图示 5.套接字相关知识点 二.HTTP         一.套接字     1. ...

  8. 20155205 郝博雅 《网络对抗技术》Exp1 PC平台逆向破解

    20155205 郝博雅 <网络对抗技术>Exp1 PC平台逆向破解 一.实验准备 1. 掌握NOP.JNE.JE.JMP.CMP汇编指令的机器码 NOP:NOP指令即"空指令& ...

  9. 微信小程序------加导航

    效果图如下 这个其实很简单 在app.json上面加点代码 "window":{ "backgroundTextStyle":"light" ...

  10. 02 of learning python

    01 input输入的是str类型 如果输入的是数字的话,要记得强制转换一下! 02 isdigit() 这个方法是用来检测字符串是否全部由数字组成 str.isdigit() 如果字符串只包含数字则 ...