题目:

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

题解:

这道题也是比较经典处理数组的,有以下两个思路。

思路1

利用HashMap,把target-numbers[i]的值放入hashmap中,value存index。遍历数组时,检查hashmap中是否已经存能和自己加一起等于target的值存在,存在的话把index取出,连同自己的index也出去,加1(index要求从1开始)后存入结果数组中返回。如果不存在的话,把自己的值和index存入hashmap中继续遍历。由于只是一遍遍历数组,时间复杂度为O(n)。

代码如下:

public int[] twoSum(int[] numbers, int target) {
int [] res = new int[2];
if(numbers==null||numbers.length<2)
return res;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < numbers.length; i++){
if(!map.containsKey(target-numbers[i])){
map.put(numbers[i],i);
}else{
res[0]= map.get(target-numbers[i])+1;
res[1]= i+1;
break;
}
}
return res;
}

思路2

又碰到敏感的关键字array和target,自然而然想到二分查找法。但是这道题不能像传统二分查找法那样舍弃一半在另外一半查找,需要一点点挪low和high指针,所以时间复杂度为O(n)。

首先先将整个list拷贝并排序,使用Arrays.Sort()函数,时间复杂度O(nlogn)

然后利用二分查找法,判断target和numbers[low]+numbers[high]。

target == numbers[low]+numbers[high], 记录copy[low]和copy[high];

target > numbers[low]+numbers[high],说明最大的和最小的加一起还小于target,所以小值要取大一点,即low++;

target > numbers[low]+numbers[high], 说明最大的和最小的加一起大于target,那么大值需要往下取一点,即high--。

再把找到的两个合格值在原list中找到对应的index,返回即可。

总共的时间复杂度为O(n+nlogn+n+n) = O(nlogn)。

代码如下:

public int[] twoSum(int[] numbers, int target) {
int [] res = new int[2];
if(numbers==null||numbers.length<2)
return res; //copy original list and sort
int[] copylist = new int[numbers.length];
System.arraycopy(numbers, 0, copylist, 0, numbers.length);
Arrays.sort(copylist); int low = 0;
int high = copylist.length-1; while(low<high){
if(copylist[low]+copylist[high]<target)
low++;
else if(copylist[low]+copylist[high]>target)
high--;
else{
res[0]=copylist[low];
res[1]=copylist[high];
break;
}
} //find index from original list
int index1 = -1, index2 = -1;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] == res[0]&&index1==-1)
index1 = i+1;
else if(numbers[i] == res[1]&&index2==-1)
index2 = i+1;
}
res[0] = index1;
res[1] = index2;
Arrays.sort(res);
return res;
}

转自:https://www.cnblogs.com/springfor/p/3859618.html

Reference:

http://blog.csdn.net/linhuanmars/article/details/19711387

http://blog.csdn.net/likecool21/article/details/10504885

leetcode series:Two Sum的更多相关文章

  1. [LeetCode 题解]:Path Sum

    前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given a bi ...

  2. LeetCode 18: 4 Sum 寻找4数和

    链接 4Sum 难度 Medium 描述 Given an array nums of n integers and an integer target, are there elements a , ...

  3. LeetCode 363:Max Sum of Rectangle No Larger Than K

    题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...

  4. LeetCode OJ:Range Sum Query 2D - Immutable(区域和2D版本)

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  5. LeetCode OJ:Range Sum Query - Immutable(区域和)

    Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -&g ...

  6. LeetCode OJ:Three Sum(三数之和)

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  7. LeetCode OJ:Path Sum II(路径和II)

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  8. LeetCode OJ:Path Sum(路径之和)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  9. leetcode笔记:Range Sum Query - Mutable

    一. 题目描写叙述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), ...

随机推荐

  1. Ceph: A Scalable, High-Performance Distributed File System译文

    原文地址:陈晓csdn博客 http://blog.csdn.net/juvxiao/article/details/39495037 论文概况 论文名称:Ceph: A Scalable, High ...

  2. 2015-2016 ACM-ICPC, NEERC, Southern Subregional Contest J Cleaner Robot

    Cleaner RobotCrawling in process... Crawling failed Time Limit:2000MS     Memory Limit:524288KB     ...

  3. CSS浮动(Float)

    定义 浮动会使元素向左或向右移动,其周围的元素也会重新排列: 浮动直到它的外边缘碰到包含框或者另一个浮动框才停止: 浮动之后的元素将围绕它,浮动之前的元素不变: 由于浮动框不在文档的普通流中,所以文档 ...

  4. json标准是双引号

    双引号才是json 的标准,单引号是不规范的(虽然在js 中是行的通的)!json 的名称和字符串值需要用双引号引起来,单引号的话,使用json.parse会出现错误

  5. 验证Oracle处理速度

    (这是2009年写的东西了,在网上看到有人对数据库批量操作的'速度'比较关注,于是就把这篇老文章整理了一下) 一.环境及前提 在244上(一台稍好一些的机器,做了RAID,机械硬盘,Raid几忘了), ...

  6. JavaScript系列-----Object之toString()和valueOf()方法 (2)

    深入理解toString()和valueOf()函数 1.我们为什么要了解这两种方法 众所周知,toString()函数和valueOf函数,这两个函数是Object类的对象生来就拥有的,而且他们还可 ...

  7. Java面试题技术类

    目录 1.面向对象编程的三大特性是什么? 2.String 和StringBuffer的区别 3.说出ArrayList,Vector, LinkedList的存储性能和特性 4.Collection ...

  8. Hibernate框架学习之注解配置关系映射

         上篇文章我们通过注解对映射了单个实体类,但是具体项目中往往实体类之间又是相互关联的,本篇文章就是从实体类之间存在的不同关联角度,具体学习下如何映射他们之间的关联,主要涉及内容如下: 单向的一 ...

  9. DIY 温控烙铁

    由于工艺原因,某处要使用200W大功率烙铁(恒温烙铁虽然有那么大功率,但没有那么大的烙铁头),只能选用普通电热丝烙铁(无温控),存在温度过高现象(造成工艺不良,同时因助焊剂+高温造成烙铁头腐蚀),逐渐 ...

  10. c#DES加密解密代码

    //加密  public string DesEncrypt(string strText, string strEncrKey)   {    byte[] byKey=null;    byte[ ...