【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, ...
随机推荐
- 在Linux中怎么把用户添加到组中
(1)添加用户test,初始密码123456,该用户的主目录为/home/share,用户的基本组为root,用户的shell为/bin/tcsh,要求将该用户加到mail和new组中.请问该怎么做啊 ...
- Ubuntu安装VMware Tools的方法
最后我将提供一个12版本的VMware Tools集合,包括了linux.iso. 背景: VMware Tools是VMware虚拟机中自带的一种增强工具,相当于VirtualBox中的增强功能(S ...
- TCP/IP详解 学习六
从ip层看路由表 选路策略 选路策略:决定把哪些路由放到路由表的规则. Ip执行选路机制,而路由守护程序则提供选路策略. Netstat –rn 打印路由表,如果没有-n命令会搜索配置文件,将网络地 ...
- Sublime text 快捷键总结
下述快捷键都是我写C++代码时发现的,是否适用其他格式(扩展名)的文件尚为未知. Basic Editing Ctrl + A 全选 Ctrl + S 保存 Ctrl + C 复制 Ctrl + V ...
- springmvc常用注解标签详解
1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ...
- android button 函数调用栈
Button button=(Button) findViewById(R.id.button);button.setOnClickListener(new Button.OnClickListene ...
- JDK安装成功了,环境变量也配置好了,测试代码也可以运行,但是打不开eclipse
解决办法:删除eclipse,重新解压后,将JDK文件夹下的jre文件夹拷贝到eclipse文件夹下,OK
- 二、Ubuntu14.04下安装Hadoop2.4.0 (伪分布模式)
在Ubuntu14.04下安装Hadoop2.4.0 (单机模式)基础上配置 一.配置core-site.xml /usr/local/hadoop/etc/hadoop/core-site.xml ...
- Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/lib/dyld_sim is not owned by root.
sudo chown -R root /Applications/Xcode6.1.1.app/ 这里把这个 /Applications/Xcode6.1.1.app/替换成你xocde据在的位置
- rsync+inotify 实现服务器之间目录文件实时同步(转)
软件简介: 1.rsync 与传统的 cp. tar 备份方式相比,rsync 具有安全性高.备份迅速.支持增量备份等优点,通过 rsync 可 以解决对实时性要求不高的数据备份需求,例如定期的备份文 ...