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

《剑指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. 《C和指针》章节后编程练习解答参考——第5章

    5.1 题目: 略 解答代码: #include <stdio.h> int main(void) { char ch; while (((ch = getchar()) != EOF) ...

  2. 练习2 I题 - 水仙花数

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Description 春天是 ...

  3. mvc Model元数据【学习笔记】

    页面中Html.Editorfor(model=>model.fieldname)这些方法,都是通过Model的元数据来生成html的,我们如果想控制最终生成的html,可以通过修改元数据来实现 ...

  4. applicationContext.xml详解 spring+mybatis+struts

    今天给大家详细解释一项关于Spring的applicationContext.xml文件,这对于初学者来说,应该是很有帮助的, 以下是详解Spring的applicationContext.xml文件 ...

  5. 根据http协议传送数据

    发送的内容: [50 4f 53 54 20 2f 64 65 78 2f 66 69 72 65 70 6f 77 65 72 20 48 54 54 50 2f 31 2e 31 0d 0a 43 ...

  6. oc调用c++接口时 报错 Undefined symbols for architecture i386:

    当在oc中调用c++中的方法时,发现说c++中的方法没定义或是找不到 Undefined symbols for architecture i386: "_desTYData", ...

  7. NWERC 2012 Problem I Idol

    又是个2-sat的模板题: 反正评委的选择必须有一个是正确的,1错误,那么2就必须正确: 这就是一个2-sat问题. 直接上白书的模板啊,不过稍微要注意的一点是对于第一个点必须要选择,不然就违反了题意 ...

  8. DPI/PPI/dp/sp/px/pt 移动设计手册

    转自DPI/PPI/dp/sp/px/pt 移动设计手册 做移动设计的同学,不管是原生app或者web app,应该对字体字号都是很头痛的问题.根本原因是,我们用唯一分辨率的电脑,设计各个不同尺寸大小 ...

  9. OnScroll与OnTouchEvent方法的区别与联系

    onScroll()方法和onTouchEvent()方法的执行过程应该是,先onTouchEvent()的ACTION_DOWN,然后是ACTION_MOVE和onScroll()方法同时进行,最后 ...

  10. 14.8.9 Clustered and Secondary Indexes

    14.8.9 Clustered and Secondary Indexes 每个InnoDB 表有一个特殊的索引称为 clustered index 用于存储数据. 通常, clustered in ...