题目:

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. EF 数据重复和缺失问题(select 错误 )

    字段有 id,name,password,sex 1.错误举例: var data = db.User.Select(d => d):   2修正 var data = db.User.Sele ...

  2. 对Spring事务一些问题的讨论

    提起spring事务,就会让人联想起四大基本特征,五个隔离级别,七大传播特性.相信大多数人都知道这些东西,但是知道是一回事情,能用好真的是另一回事了.在使用Spring事务的时候,我曾遇到过几个比较严 ...

  3. 不借助vue-cli,自行构建一个vue项目

    前言: 对于刚刚接触vue的同学来说,直接用官方的构建工具vue-cli来生成一个项目结构会存在一些疑惑,比如:   .vue组件 为什么可以写成三段式(tempalte.script.style)? ...

  4. Rank of Tetris

    Rank of Tetris Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...

  5. 「设计模式」JavaScript - 设计模式之单例模式与场景实践

    单例介绍 上次总结了设计模式中的module模式,可能没有真真正正的使用在场景中,发现效果并不好,想要使用起来却不那么得心应手, 所以这次我打算换一种方式~~从简单的场景中来看单例模式, 因为Java ...

  6. 关于缓存问题:js清除缓存

    css并行加载,js串行加载(会阻塞页面) 清除缓存的问题: 1.一般手动清除,浏览器缓存 2.js代码清除缓存(原理:增加了一个参数,且该参数是一个随机数,每次都不一样,所以每次的请求参数都不一样, ...

  7. URLs对象 blob URL

    把指向数据的URL保存到file或者blob对象里,好处就是不需要先文件读取内容然后才能用.   function createObjectURL(blob){if (window.URL){retu ...

  8. 从一个实例谈谈postgresql索引锁

    最近客户在使用我司开发的数据库时,报告了如下问题(也不能算是问题,就是疑惑吧),环境如下: OS : Red Hat Enterprise Linux Server release 6.7 (Sant ...

  9. FTP配置的一些笔记

    1.必须关闭防火墙 iptables -F iptables -X iptables -Z vi /etc/selinux/config          SELINUX=disabled seten ...

  10. Linux 新建文件/文件夹,删除文件文件夹,查找文件 打开文件

    1.新建文件夹:mkdir xx 2.新建文件: touch 1.py 3.删除文件/文件夹: rm -r xx  rm 1.py 4.打开文件:cat 1.py 只显示前几行 :head -2 1. ...