leetcode — two-sum
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的更多相关文章
- 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 ...
- 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)
剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [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 ...
- [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 ...
- [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [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 ...
- [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [LeetCode] Combination Sum III 组合之和之三
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
随机推荐
- 移动端各种滚动场景需求的插件better-scroll
移动端各种滚动场景需求的插件: 文档地址: better-scroll:https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/#better- ...
- window下github的学习心得
准备工作: 安装git: 1.下载地址:http://msysgit.github.io/ 2.安装:本人是一路next的,现在没发现有什么问题.详细的安装过程参考:https://jingyan.b ...
- C语言函数指针与 c#委托和事件对比
C语言: 函数指针可以节省部分代码量,写类似具有多态的函数,比如要比较最大值,如果不用函数指针就只能写比较某一类型比如int类型的max函数,这个max无法比较string的大小.函数指针的意义就不多 ...
- unic
在线考试 答题剩余时间0小时51分18秒 考生须知 1.本次考试结束后,剩余补考次数:2次 2.考试时间为60分钟,超时系统自动交卷 3.本次考试满分100分(5*20道),60分通过考试 1. (单 ...
- vscode 添加 includePath
使用vscode打开C项目时,vscode无法找到头文件路径,提示:configure includePath for better intellisense results 解决: 编辑~/.vsc ...
- 浅析列表页请求优化(history API)
最近搞了下列表页请求的功能,并做了一下调研整理,记此文备忘. 列表页请求的功能到处可见,比如在博客园. 点击相应的页码,页面返回相应的内容,看上去似乎大同小异,但是一些小的细节还是可以区分优劣. fu ...
- numpy 库简单使用
numpy 库简单使用 一.numpy库简介 Python标准库中提供了一个array类型,用于保存数组类型的数据,然而这个类型不支持多维数据,不适合数值运算.作为Python的第三方库numpy便有 ...
- 一、Java和JavaScript
JavaScript诞生于1995年,所以他得叫我一声姐姐,(*^__^*) .当时它的主要任务就是表单验证,在还没JavaScript的时候,进行表单验证的时候必须要把数据提交到服务器,才能进行表单 ...
- elasticSearch新认知
之前已经学习使用过ElasticSearch的使用,今天补充巩固一下... 上一次的环境是在 linux下使用 EalsticSearch(安装教程详见:https://www.cnblogs.com ...
- 隔壁小孩都要知道的Drupal配置
i春秋作家:Arizona 原文来自:隔壁小孩都要知道的Drupal配置 隔壁小孩都要知道的Drupal配置 Drupal是一个开源的PHP内容管理系统,具有相当复杂的架构.它还具有强大的安全模型.感 ...