问题描写叙述:在一个数组(无序)中高速找出两个数字,使得两个数字之和等于一个给定的值。如果数组中肯定存在至少一组满足要求。

《剑指Offer》P214(有序数组) 《编程之美》P176

Que:Given an array of integers, find twonumbers such that they add up to a specific target number.

The function twoSum should return indices ofthe two numbers such that they add up to the target, where index1 must be lessthan index2. Please note that your returned answers
(both index1 and index2)are not zero-based.

You may assume that each input would haveexactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

一、暴力穷举法 时间复杂度:O(N^2)

代码:

// 暴力解法。时间复杂度(O(n^2)),性能太差无法通过
public int[] twoSum1(int[] numbers, int target) {
if (numbers != null) {
int i, j = 0;
for (i = 0; i < numbers.length; i++) {
for (j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
int[] result = { ++i, ++j };
return result;
}
}
}
}
return null;
}

二、Hash表法,以空间换时间:时间复杂度:O(N)空间复杂度O(N)

更快的查找方法:hash表,给定一个数字,依据hash映射查找还有一个数字是否在数组中,仅仅需O(1)的时间,但须要承担O(N)的hash表存储空间。

C++能够使用STL中的hash_map,java使用HashMap

代码:

// 使用HashMap(查找的时间复杂度为O(1))
// 由题目如果知仅仅有一对数满足该情况,故每一个数都是唯一的,不存在重数的情况
public int[] twoSum2(int[] numbers, int target) {
if (numbers != null) {
// 由于Hashmap仅提供通过key获得value,故
// HashMap value放置与numers[index]匹配的数值,key放置index;,故
// 在以下循环时每一次查询map中的value是否有相等的值。有即相互匹配
// 其思想在于用index的value表示数组中的该数据,map中的key与之匹配,并在数组中寻找匹配值
HashMap<Integer, Integer> num_map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (num_map.containsKey(numbers[i])) {
int index = num_map.get(numbers[i]);
int[] result = { ++index, ++i };
return result;
} else {
num_map.put(target - numbers[i], i);
}
}
}
return null;
}

三、非常easy能够想到先将查找的数组排序,然后用二分查找等方法进行查找。本题中能够直接对两个数字的和进行一个有序的遍历(当然和不用所有真正计算出来)。

1.首先对数组进行排序。时间复杂度为O(NlogN)

2.然后从i=0,j=end開始和末位的两个数字開始。计算两个之和sum。若sum大于目标值target,则须要一个较小的因子,j--;反之,i++;直至找到终于的结果。

代码:(这里没有返回相应原始位置。仅仅是返回了两个相应数据)

public int[] twoSum3(int[] numbers, int target) {
if (numbers != null) {
// 先进行排序,这里使用归并排序
new Merge_Sort().Merge_Sort(numbers, new int[numbers.length], 0,
numbers.length - 1);
// 实现该查找算法
int ahead = numbers.length - 1;
int behind = 0;
while (ahead > behind) {
// 注意result和要考虑两个较大int相加溢出的问题
long result = numbers[ahead] + numbers[behind]; if (result == target) {
int[] sum = { numbers[behind] , numbers[ahead] };
//假设要返回两个原始位置值,是否意味着还是又一次进行两次查询;
return sum;
} if (result < target) {
behind++;
} else {
ahead--;
}
}
} return null;
}

leetcode-1 Two Sum 找到数组中两数字和为指定和的更多相关文章

  1. Java 找到数组中两个元素相加等于指定数的所有组合

    思路1:可以用hash表来存储数组中的元素,这样我们取得一个数后,去判断sum - val 在不在数组中,如果在数组中,则找到了一对二元组,它们的和为sum,该算法的缺点就是需要用到一个hash表,增 ...

  2. LeetCode 421. 数组中两个数的最大异或值(Maximum XOR of Two Numbers in an Array) 71

    421. 数组中两个数的最大异或值 421. Maximum XOR of Two Numbers in an Array 题目描述 给定一个非空数组,数组中元素为 a0, a1, a2, - , a ...

  3. 2016网易实习生编程题:数组中两个数的和等于sum

    题目 找出数组中两个数的和等于sum的这两个数 解题 这个题目做过很多次了,利用HashMap,key为 sum-A[i] value为 i 当 加入HashMap时候A[i] 已经存在map中,ge ...

  4. Leetcode 421.数组中两数的最大异或值

    数组中两数的最大异或值 给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 . 找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ...

  5. Java实现 LeetCode 421 数组中两个数的最大异或值

    421. 数组中两个数的最大异或值 给定一个非空数组,数组中元素为 a0, a1, a2, - , an-1,其中 0 ≤ ai < 231 . 找到 ai 和aj 最大的异或 (XOR) 运算 ...

  6. LeetCode 260 Single Number III 数组中除了两个数外,其他的数都出现了两次,找出这两个只出现一次的数

    Given an array of numbers nums, in which exactly two elements appear only once and all the other ele ...

  7. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  8. 求数组中两两相加等于20的组合(Python实现)

    题目 求数组中两两相加等于20的组合. 例:给定一个数组[1, 7, 17, 2, 6, 3, 14],这个数组中满足条件的有两对:17+3=20, 6+14=20. 解析 分为两个步骤: 先采用堆排 ...

  9. 【ShareCode】不错的技术文章 -- 如何使用异或(XOR)运算找到数组中缺失的数?

    如何使用异或(XOR)运算找到数组中缺失的数? 今天给大家分享一篇关于使用XOR(异或)运算找到数组中缺失的数的问题. 在一次Javascript面试中,有这么一个问题: 假设有一个由0到99(包含9 ...

随机推荐

  1. 图片延迟加载插件jquery.lazyload.js的使用方法

    最新版的jquery.lazyload.js已不再是伪的延迟加载了 一.请按照基本使用方法说明设置 //载入JavaScript 文件 <script src="jquery.js&q ...

  2. input 标签的class 失效

    今天CSS网页的是时候,动态添加input class属性失效, 检查原因是因为之前对此input 使用了  input[type='checkbox'] 应该给其定义一个CLASS,其后面动态添加C ...

  3. 2016多校联合训练contest4 1012Bubble Sort

    Bubble Sort Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Tota ...

  4. linq 多个left join 和 sql union all -> linq union 方法

     (   from s in Base_SysMenus   join r in Base_RoleRights on s.Menu_Id equals r.Menu_Id into temp   f ...

  5. VisualSVN Server 从此告别SVN记事本配置

    http://www.visualsvn.com/downloads/ 注意下载的是Server版本,他还会提供一个visual Studio的插件:   安装完毕后,可以在管理界面进行角色添加,创建 ...

  6. Scut:账号服务器问题修正

    姑且记录一下,以防未来出现bug回来看看今天改了哪些. 原 Scut 账服是应用于 渠道频道 的账号服务器,每天会发放大量的游客账号,它有一个"自动将已经被注册了一段时间的游客账号再重新推送 ...

  7. bzoj 3751: [NOIP2014]解方程 同余系枚举

    3.解方程(equation.cpp/c/pas)[问题描述]已知多项式方程:a ! + a ! x + a ! x ! + ⋯ + a ! x ! = 0求这个方程在[1, m]内的整数解(n 和 ...

  8. BZOJ 1876 SuperGCD

    Description Sheng bill有着惊人的心算能力,甚至能用大脑计算出两个巨大的数的GCD(最大公约数)!因此他经常和别人比赛计算GCD.有一天Sheng bill很嚣张地找到了你,并要求 ...

  9. 解决poi导出Excel异常org.openxmlformats.schemas.spreadshe

    JAVA报表 POI未捕获到 servlet OUTEXCEL 的其中一个服务方法中抛出的异常.抛出的异常:java.lang.NoClassDefFoundError: org.openxmlfor ...

  10. keil教程

    KEIL C51标准C编译器为8051微控制器的软件开发提供了C语言环境,但是界面是英文的好多初学者看很多教程都是一头雾水,这个相对简单的教程.KEIL C51编译器的功能不断增强,使你可以更加贴近C ...