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 ...
随机推荐
- 移动端H5页面禁止长按复制和去掉点击时高亮
/*设置IOS页面长按不可复制粘贴,但是IOS上出现input.textarea不能输入,因此将使用-webkit-user-select:auto;*/ *{ -webkit-touch-callo ...
- jq 下拉框获取选中自定义属性值
// 下拉框发送改变后 获取选择的信息 <div class="form-group"> <label class="col-sm-3 control- ...
- php学习备注笔记
一: PHP内核相关 http://blog.csdn.net/ywh147/article/details/40188411 [深入PHP内核(二)——SAPI探究] http://www.nowa ...
- redis_字典_哈希hash
字典.哈希表基本数据结构 redis字典使用哈希表作为底层实现,基本结构就是数组+散列 typedef struct dictht { // 哈希表数组 dictEntry **table; // 哈 ...
- 关于数据库连接时URL的问题
最近在写一个简单的增删改查的代码时,遇到保存的中文都会变成问号(?),由于刚开始只是一些数据的保存,所以认为之后只要对数据库的编码进行修改即可,但是后来要对数据进行查找的时候发现根本查找不到, 当时用 ...
- 【Android开源库】 PagerSlidingTabStrip从头到脚
简介 PagerSlidingTabStrip,是我个人经常使用到的一个和ViewPager配合的页面指示器,可以满足开发过程中常用的需求,如类似于今日头条的首页新闻内容导航栏等等,之前自己开发的Ju ...
- python图形界面编程
EasyGui(easygui-docs-0.96\tutorial\index.html) import easygui as g import sys while 1: g.msgbox('mes ...
- RabbitMQ 使用主题进行消息分发
在上篇文章RabbitMQ消息队列(五):Routing 消息路由 中,我们实现了一个简单的日志系统.Consumer可以监听不同severity的log.但是,这也是它之所以叫做简单日志系统的原因, ...
- 《Node.js高级编程》之Node 核心API基础
Node 核心API基础 第三章 加载模块 第四章 应用缓冲区 第五章 事件发射器模式简化事件绑定 第六章 使用定时器制定函数执行计划 第三章 加载模块 本章提要 加载模块 创建模块 使用node_m ...
- 使用python访问网络上的数据
这两天看完了Course上面的: 使用 Python 访问网络数据 https://www.coursera.org/learn/python-network-data/ 写了一些作业,完成了一些作业 ...