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 ...
随机推荐
- java+phantomjs实现动态网页抓取
1.下载地址:http://phantomjs.org/download.html 2.java代码 public void getHtml(String url) { HTML="&quo ...
- WebApi零碎总结
1.如果Content-Type是application/json,而POST和PUT的参数是[FromBody] string value,那么如果curl -d的值是'{"Name&qu ...
- go 切片的创建方式
切片的创建方式现知道的有下面几种方式,切片为指针类型,从数组中得到的切片修改元素值时,原数组也会发生变化(数组为非指针类型) package main import "fmt" f ...
- python_flask框架学习之路(1)
1.初识web,了解utl . 术语: scheme://host:port/path?query-string=xxx#yyyy 例子:https://i.cnblogs.com/EditArtic ...
- bzoj4445(半平面交)
列出式子对一下然后上半平面交 #include<iostream> #include<cstring> #include<cmath> #include<cs ...
- windows下qt的.exe的dll文件怎么配齐
用qt自带的windeploy工具即可 win键打开开始菜单 找到qt目录下的qt for desktop(mingw)并打开 qtcreater或者vs打开要部署的项目,构建成release模式,运 ...
- BABOK概述
BABOK概述 BABOK(Business Analysis Body of Knowlodge: 业务[或商业]分析知识体系)是由位于加拿大的IIBA(International Institut ...
- Linux的内存机制(转载)
今天我们来谈谈Linux的内存机制. 首先我们理一下概念 一.什么是linux的内存机制? 我们知道,直接从物理内存读写数据要比从硬盘读写数据要快的多,因此,我们希望所有数据的读取和写入都在内存完成, ...
- 因为曾经装过Mysql导致再次装时windows无法启动MySQL服务报错1067的解决方法
找到这里 MySQL右击属性 检查这里的可执行文件的路径是否正确,因为我这里显示的是原先的文件夹所以会一直启动失败,修改一下 这里你去百度经验 windows服务修改可执行文件路径 网址https:/ ...
- 关于oracle数据库的小知识
--查询语句:select 列名/通配符/列别名/表达式 from 表名 (修饰/限制语句)select * from tab;select tname from tab;--指定的列select t ...