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

解题思路一

先对数组排序,然后用left和right指针找到目标值,最后找到目标值的位置即可。

C++代码如下:

 #include<vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int left = , right = numbers.size() - , sum;
vector<int> sorted(numbers);
sort(sorted.begin(), sorted.end());
vector<int> index;
while (left < right) {
sum = sorted[left] + sorted[right];
if (sum == target) {
for (int i = ; i < numbers.size(); i++) {
if (numbers[i] == sorted[left])
index.push_back(i + );
else if (numbers[i] == sorted[right])
index.push_back(i + );
if (index.size() == )
return index;
}
}
else if (sum > target)
right--;
else
left++;
}
}
};

解题思路二

由于图的遍历所需时间开销比较固定,因此可以使用HashMap,以数组的内容为key,以数组下标为Value,这样时间复杂度为O(n)。

因此,第一步:将数组元素存入HashMap里面;第二步:将对于numbers[]的每个值,用target-numbers[i]在图中进行遍历,如果发现存在这样的值,并且这样的值不是numbers[i]对应的节点本身,那么,遍历结束。

Java代码如下:

public class Solution {
static public int[] twoSum(int[] numbers, int target) {
int[] a={0,0};
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<numbers.length;i++){
map.put(numbers[i], i);
}
for(int i=0;i<numbers.length;i++){
int gap=target-numbers[i];
if((map.get(gap)!=null)&&map.get(gap)!=i){
a[0]=i+1;
a[1]=map.get(gap)+1;
break;
}
}
return a;
}
}

C++实现如下:

 #include<vector>
#include<unordered_map>
class Solution {
private:
unordered_map<int, int> numMap;
vector<int> res;
public:
vector<int> twoSum(vector<int> &numbers, int target) {
for (int i = ; i < numbers.size(); i++)
numMap.insert(unordered_map<int, int>::value_type(numbers[i], i));
for (int i = ; i < numbers.size(); i++) {
unordered_map < int, int >::iterator iter;
int gap = target - numbers[i];
iter = numMap.find(gap);
if (iter != numMap.end()&&numMap[gap]!=i) {
res.push_back(i+);
int num2 = numMap[gap]+;
if(num2>i+)
res.push_back(num2);
else
res.insert(res.begin(),num2);
return res;
}
}
}
};

【JAVA、C++】LeetCode 001 Two Sum的更多相关文章

  1. 【JAVA、C++】LeetCode 005 Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  2. 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  3. 【JAVA、C++】LeetCode 022 Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  4. 【JAVA、C++】LeetCode 010 Regular Expression Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  5. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  6. 【JAVA、C++】LeetCode 007 Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...

  7. 【JAVA、C++】LeetCode 006 ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  8. 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

  9. 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

随机推荐

  1. Bzoj1115 石子游戏Kam

    这是道权限题,差评. 题目说明引自ZYF-ZYF Description 有N堆石子,除了第一堆外,每堆石子个数都不少于前一堆的石子个数.两人轮流操作每次操作可以从一堆石子中移走任意多石子,但是要保证 ...

  2. IOS基础之 (九) Foundation框架

    一NSNumber 类型转换 NSNumber 把基本数据类型包装成一个对象类型.NSNumber之所以可以(只能)包装基本数据类型,是因为继承了NSValue. @20 等价于 [NSNumber ...

  3. HTTP负载测试——Tsung

    参考资料:http://blog.jobbole.com/87509/ 如何生成每秒百万级别的 HTTP 请求? 在进行负责测试时要牢记一件重要的事:你能在 Linux 上建立多少个 socket 连 ...

  4. 网友微笑分享原创Jquery实现瀑布流特效

    首先非常感谢网友微笑的无私分享,此Jquery特效是一款非常流行和实用的瀑布流布局,核心代码只有几十行,是我见过代码量最少的瀑布流布局,非常适合网友们学习哦,希望大家好好看一下这个Jquery特效的原 ...

  5. 在CentOS 7上利用systemctl添加自定义系统服务

    每一个服务以.service结尾,一般会分为3部分:[Unit].[Service]和[Install],具体内容如下: [Unit]Description=*****After=network.ta ...

  6. mybatis 使用resultMap实现数据库的操作

    resultType:直接表示返回类型 resultMap:对外部resultMap的引用 二者不能同时使用 创建一个实体类Role和User public class Role { private ...

  7. 让VisualVM+BTrace进入unsafe mode

    让VisualVM+BTrace进入unsafe mode http://kenai.com/projects/btrace/pages/UserGuide BTrace很强大,但有很多安全限制,比如 ...

  8. swift中文文档- 类型转换

    未翻译完 待续(英语烂,求斧正) Type Casting 类型转换 Type casting is a way to check the type of an instance, and/or to ...

  9. linux的vnc- rdesktop远程登录windows桌面

    使用vnc来实现任何平台之间(windows, linux, mac等)的远程桌面互访 vnc:virtual network computing 分 vnc server和 vnc client 在 ...

  10. Linux的一些基础

    想要知道你的 Linux 支持的文件系统有哪些,可以察看底下这个目录: [root@www ~]# ls -l /lib/modules/$(uname -r)/kernel/fs 系统目前已加载到内 ...