【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, ...
随机推荐
- json2.js的初步学习与了解
json2.js的初步学习与了解,想要学习json的朋友可以参考下. json2.js的初步学习与了解 1.)该js的下载地址是:http://www.json.org/json2.js 2.)在页面 ...
- BZOJ2654 tree
Description 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. Input 第一行V,E,need分别表示点数,边数和需要的白色 ...
- poj1056 (Trie入门)寻找字符串前缀
题意:给你一堆字符串,问是否满足对于任意两个字符串a.b,a不是b的前缀 字典树==前缀树==Trie树 trie入门题,只用到了insert和query操作 #include <cstdio& ...
- --Dirring love 音乐(01背包问题)
解题思路: dp[i][j] 前 i 首歌放入 j 容量中的最大热情度. 前 i 首歌 放到 j 容量中 dp[i][j]= dp[i-1][j-m[i]]+r[i] (注意:如果 j 容量 &l ...
- textView中判断文本长度,自定义表情长度为1,emoj表情长度为1,输入限制
static const int MAX_LIMIT_NUMS = 100; /**< 输入个数限制 */ // self.inputNumberTipsLabel 控制器的view上一个用 ...
- Nginx Http框架的理解
Nginx Http框架的理解 HTTP框架是Nginx基础框架的一部分,Nginx的其它底层框架如master-worker进程模型.event模块.mail 模块等. HTTP框架代码主要有2个模 ...
- C# 三种实现抖屏的方式
//int a = -2; //this.BringToFront(); //for (int i = 0; i < 20; i++) //{ // a = -a; // this.Locati ...
- jQuery Uploadify在ASP.NET MVC中的使用
感谢http://www.cnblogs.com/libingql/archive/2012/09/11/2681007.html 除此之外,给大家推荐一个: http://gallery.kissy ...
- Android-深入理解android自定义属性(AttributeSet,TypedArray)
属性 自定义属性,首先要定义出来属性,我们新建一个attrs.xml: <?xml version="1.0" encoding="utf-8"?> ...
- 利用SecureCRT上传、下载文件(使用sz与rz命令)
sz用法: 下载一个文件 sz filename 下载多个文件 sz filename1 filename2 下载dir目录下的所有文件,不包含dir下的文件夹 sz dir/* 下载文件存放位置在s ...