题目:

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. C#匹配标签正则,获取标签的值

    比如要获取: <color=#50cccc>头盔坐标:(-0.6, 1.0, 1.2)</color><color=#3d85c6>头盔方向(-0.2, 0.1, ...

  2. iOS下OpenCV开发用OC还是Swift

    本文为作者原创,转载请注明出处(http://www.cnblogs.com/mar-q/)by 负赑屃 其实标题中这个问题并不准确,准确的说法应该是iOS下的OpenCV开发是使用OC还是Swift ...

  3. 老的工程移植到AndroidStudio需要修改的注意事项

    之前老的工程用android-apt编译,如果要在新的AndroidStudio编译至少需要修改一下几部分: 1. 修改project里的build.gradle dependencies { cla ...

  4. my dream

    我的梦想(践踏一切可以践踏的,放弃一切必须放弃的,然后朝着自己认为的方向努力,只要自己认为对了就可以了(但是最好能考虑方面全一点,这就叫尽力了)我想要的生活怎么那么醉我想要的食物怎么那么碎我最爱的女孩 ...

  5. angular2安装笔记

    主要摘自:http://www.runoob.com/angularjs2/angularjs2-typescript-setup.html http://blog.csdn.net/lgpwwa/a ...

  6. Leetcode题解(十四)

    39.Combination Sum 题目 题目要求找出和为target的数字组合,并且每个整数可以多次使用.仔细思考可以发现,这道题目可以采用递归的方法来完成,比如举的例子,target=7,一开始 ...

  7. AMD 和 CMD 的区别

    AMD 规范在这里:https://github.com/amdjs/amdjs-api/wiki/AMD CMD 规范在这里:https://github.com/seajs/seajs/issue ...

  8. 分享如何将git项目导入GitHub(附创建分支)

    前言:我们应该很多都会有自己的私有项目,大多情况都是存放在自己的硬盘中,今天我分享一下怎么讲自己的私有项目更新到GitHub上,这样再也不用担心项目丢失了. 一:下载git 下载链接git链接,根据自 ...

  9. RPA(Robotic Process Automation)的概要介绍

    最近因为公司业务的需要,开始关注RPA的内容,奈何国内相关的信息太少,只能硬着头皮啃英文了. 下面记录的内容作为学习笔记,有不对的地方请大家指教. 首先RPA(Robotic Process Auto ...

  10. Winform C# 简单实现子窗口显示进度条

    主窗口代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data ...