leetcode series:Two Sum
题目:
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的更多相关文章
- [LeetCode 题解]:Path Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a bi ...
- LeetCode 18: 4 Sum 寻找4数和
链接 4Sum 难度 Medium 描述 Given an array nums of n integers and an integer target, are there elements a , ...
- LeetCode 363:Max Sum of Rectangle No Larger Than K
题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- leetcode笔记:Range Sum Query - Mutable
一. 题目描写叙述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), ...
随机推荐
- 关于celery django django-celery版的搭配的报错问题及解决方法
G:\python3_django\DFpro\mypro (win)(py3_django) λ python manage.py celery worker --loglevel=infoTrac ...
- For循环的实质
For循环的实质 1.调用可迭代对象的iter方法返回一个迭代器对象 2.不断调用迭代器对象的next方法 3.处理StopIteration
- 温故而知新 Volley源码解读与思考
相比新的网络请求框架Volley真的很落后,一无是处吗,要知道Volley是由google官方推出的,虽然推出的时间很久了,但是其中依然有值得学习的地方. 从命名我们就能看出一些端倪,volley中 ...
- java中matches的用法
在java中,时常会用到查看一个字符串是否是数字,这时就可以用到matches()函数. 具体实例如下: public boolean string_matches(String amatch) { ...
- iOS之 Category 属性 的理解
在 Objective-C 中可以通过 Category 给一个现有的类添加属性,但是却不能添加实例变量 反正读第一遍的时候我是有点晕的,可以添加“属性”,然后又说“添加实例变量”,第一感觉就好像 有 ...
- Java基础笔记12
1.自定义异常. 定义一个类,让该类继承Exception.并写出该类的所有的构造函数.2.IO流. java.io 文件类.File 字节输入和输出流 InputStream OutputStrea ...
- 本地文件与服务器文件同步shell脚本。
#!/bin/sh read -t 30 -p "请输入项目名:" name echo -e "\n" echo "项目名为:$name" ...
- java中this关键字解析
由于this关键字在Java程序中经常见到,笔者索性把它的用法总结一下,来和大家一到互相学习一下.总的来说this用在下面几个地方: (1)当局部变量和成员变量同名的时候,需要用this来加以区分 如 ...
- Leetcode题解(三)
8.String to Integer (atoi) 题目 这道题目关键是要考虑清楚各种输入用例.针对每一种情况,函数都能处理,也就是函数鲁棒性很高.代码如下: class Solution { pu ...
- 工控SCADA模型 基于HTML5 Canvas WebGL制作摩托车
工业方面制作图表,制作模型方面运用到 3d 模型是非常多的,在一个大的环境中,构建无数个相同的或者不同的模型,构建起来对于程序员来说也是一件相当头疼的事情,我们利用 HT 帮大家解决了很大的难题,以下 ...