【JAVA、C++】LeetCode 001 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
解题思路一
先对数组排序,然后用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的更多相关文章
- 【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 ...
- 【JAVA、C++】LeetCode 002 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 【JAVA、C++】LeetCode 022 Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- 【JAVA、C++】 LeetCode 008 String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【JAVA、C++】LeetCode 007 Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...
- 【JAVA、C++】LeetCode 006 ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- 【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 ...
- 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
随机推荐
- Microsoft Hololens 入门系列-01-开篇
1.能做什么 Microsoft HoloLens是第一台运行Windows10系统的全息计算机,它已经不受任何限制——没有线缆和听筒,并且不需要连接电脑.Microsoft Hololens能够让你 ...
- eclipse中建python项目并运行
1. Help → Install New Software 2.Enter http://pydev.org/updates 3.点击Click "Next" and " ...
- java 内存分析
Java堆内存(heap memory)的十个要点: 1. Java堆内存是操作系统分配给JVM的内存的一部分. 2. 当我们创建对象时,它们存储在Java堆内存中. 3. 为了便于垃圾回收,Java ...
- C#实现自动升级(附源码)
http://blog.csdn.net/zhuweisky/article/details/50439386 OAUS
- photon mapping阶段性总结
PM算法看了这么久,也该是到了总结的时候了.自己实现的是PPPM(Probabilistic progressive photon mapping)的一个简化形式.之所以是简化形式是由于我的光子搜集时 ...
- sql 树 递归
sql 树 递归 with SubQuery(No,Name,ParentNo) as ( ' union all select A.No,A.Name,A.ParentNo from [Port_D ...
- linux进程调度之 FIFO 和 RR 调度策略
转载 http://blog.chinaunix.net/uid-24774106-id-3379478.html linux进程调度之 FIFO 和 RR 调度策略 2012-10-19 18 ...
- Visual Studio 2013 中 mysql 使用 EF6
1.web.config <configSections> <!-- For more information on Entity Framework configuration, ...
- jQuery 事件用法详解
jQuery 事件用法详解 目录 简介 实现原理 事件操作 绑定事件 解除事件 触发事件 事件委托 事件操作进阶 阻止默认事件 阻止事件传播 阻止事件向后执行 命名空间 自定义事件 事件队列 jque ...
- javascript和HTML5上传图片之前实现预览效果
一:FileList对象与file对象 FileList对象表示用户选择的文件列表,在HTML4中,file控件内只允许放置一个文件,但是到了HTML5中,通过添加multiple属性,file控件内 ...