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. Codeforces 548B Mike and Fun

    传送门 B. Mike and Fun time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  2. Mysql 学习-索引的设计原则

    索引的设计不合理或者缺少索引都会对数据库和应用程序的性能造成障碍.高效的索引对获的良好性能非常重要.设计索引是,应该考虑一下准则: (1)索引并非语讹夺越好,若一个表中有大量索引,不仅占用磁盘空间,而 ...

  3. abstract 类也可以继承 实体类

    public class BaseReq { public String UserId { get; set; } public BaseReq() { } } public abstract cla ...

  4. 使用Tengine替代Nginx作为负载均衡服务器

    Tengine是由淘宝网发起的Web服务器项目.它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能和特性.Tengine的性能和稳定性已经在大型的网站如淘宝网,天猫商城等得到了很好的检 ...

  5. 伪分布模式下执行wordcount实例时报错解决办法

    问题1.不能分配内存,错误提示如下: FAILEDjava.lang.RuntimeException: Error while running command to get file permiss ...

  6. Redis Cluster 理论知识

    http://www.ttlsa.com/redis/redis-cluster-theoretical-knowledge/ Redis 集群的 TCP 端口(Redis Cluster TCP p ...

  7. ping 和 traceroute 命令

    ping 和 traceroute 命令 ping 程序 就是发送一个ICMP查询报文给某服务器,以测试该服务器是否可达. 当返回ICMP回显应答时,要打印出序列号.TTL,和往返时间:   [roo ...

  8. Linux中表示“时间”的结构体和相关函数

    转载于:http://blog.chinaunix.net/uid-25909722-id-2827364.html      Linux中表示“时间”的结构体和相关函数 2011-09-13 17: ...

  9. 15个超实用的php正则表达式

    在这篇文章里,我已经编写了15个超有用的正则表达式,WEB开发人员都应该将它收藏到自己的工具包. 验证域名 检验一个字符串是否是个有效域名. $url = "http://komunitas ...

  10. Fortran向C传递NULL值

    在很多C或C++的头文件定义中,NULL被指定定义为0,这里不再具体展开 gfortran的手册关于iso c binding的章节,定义NULL如下 Moreover, the following ...