[LeetCode] 1. Two Sum 两数和
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给一个没排序的包含整数的数组,找出使得两个数的和是给定值的indices。假设每个输入只有一个答案, 同一元素不会用到两次。
解法:
1. 暴力解法,两个for循环遍历,两个数相加和目标数比较。Time: O(n^2)
2. 先对数组快速排序,然后用两个指针分别指向头和尾,每次比较头尾两个数的和,如果比target小,头标记右移,如果大,尾标记左移。需要注意记录快速排序前后数字的位置变化。Time: O(n)
3. 先遍历一遍数组,建立数字和index的HashMap,然后再遍历一遍,开始查找target - num[i]是否在map中,如果在,找到并返回index。Time: O(n) Space: O(n)
Java:解法1
public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}
Java:解法2
class Pair implements Comparable<Pair>{
public int number;
public int idx;
public Pair(int number, int idx){
this.number = number;
this.idx = idx;
}
public int compareTo(Pair other){
return this.number - other.number;
}
}
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
Pair[] pairs = new Pair[n];
for(int i = 0; i < n; ++i){
pairs[i] = new Pair(numbers[i], i + 1);
}
Arrays.sort(pairs);
int [] result = new int[2];
int begin = 0;
int end = n - 1;
while(begin < end){
if(pairs[begin].number + pairs[end].number < target){
begin++;
}
else if (pairs[begin].number + pairs[end].number > target){
end--;
}
else{
if(pairs[begin].idx > pairs[end].idx){
result[0] = pairs[end].idx;
result[1] = pairs[begin].idx;
}else{
result[0] = pairs[begin].idx;
result[1] = pairs[end].idx;
}
break;
}
}
return result;
}
}
Java: 解法3,Two loops
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
m.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i) {
int t = target - nums[i];
if (m.containsKey(t) && m.get(t) != i) {
res[0] = i;
res[1] = m.get(t);
break;
}
}
return res;
}
}
Java: 解法3,one loop
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}
}
Python:
class Solution(object):
def twoSum(self, nums, target):
hash_map = {}
for i, v in enumerate(nums):
hash_map[v] = i for index1, value in enumerate(nums):
if target - value in hash_map:
index2 = hash_map[target - value]
if index1 != index2:
return [index1, index2]
Python:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
lookup[num] = i
Python: wo
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i in range(len(nums)):
if target - nums[i] in lookup:
return [lookup[target - nums[i]], i]
lookup[nums[i]] = i
Python:
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> lookup;
for (int i = 0; i < nums.size(); ++i) {
if (lookup.count(target - nums[i])) {
return {lookup[target - nums[i]], i};
}
lookup[nums[i]] = i;
}
return {};
}
};
相似题目:
[LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组
[LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
[LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
All LeetCode Questions List 题目汇总
[LeetCode] 1. Two Sum 两数和的更多相关文章
- [LeetCode] 1. Two Sum 两数之和
Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...
- [LeetCode]1.Two Sum 两数之和&&第一次刷题感想
---恢复内容开始--- 参考博客: https://www.cnblogs.com/grandyang/p/4130379.html https://blog.csdn.net/weixin_387 ...
- [LeetCode] 1.Two Sum 两数之和分析以及实现 (golang)
题目描述: /* Given an array of integers, return indices of the two numbers such that they add up to a sp ...
- 【LeetCode】Two Sum(两数之和)
这道题是LeetCode里的第1道题. 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会 ...
- [leetcode]1. Two Sum两数之和
Given an array of integers, return indices of the two numbers such that they add up to a specific t ...
- [LeetCode]1.Two Sum 两数之和(Java)
原题地址:two-sum 题目描述: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标. 你可以假设每 ...
- LeetCode刷题 1. Two Sum 两数之和 详解 C++语言实现 java语言实现
1. Two Sum 两数之和 Given an array of integers, return indices of the two numbers such that they add up ...
- 【LeetCode】1. Two Sum 两数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:two sum, 两数之和,题解,leetcode, 力 ...
- Leetcode:0002(两数之和)
LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...
随机推荐
- PAT甲级1001水题飘过
#include<iostream> using namespace std; int main(){ int a, b; while(scanf("%d%d", &a ...
- php的希尔排序
算是改进了的插入排序, 从性能时间上来看,也确实更有改进. 但比起php内置的功能,性能还有十倍之差呢 <?php /** * 原理:把排序的数据根据增量分成几个子序列,对子序列进行插入排序, ...
- 项目Alpha冲刺 10
作业描述 课程: 软件工程1916|W(福州大学) 作业要求: 项目Alpha冲刺(团队) 团队名称: 火鸡堂 作业目标: 介绍第10天冲刺的项目进展.问题困难和心得体会 1.团队信息 队名:火鸡堂 ...
- 自动生成百度小程序sitemap.txt文件路径
因为业务需要,需要在目前项目上开发一个百度小程序,百度智能小程序上线了,但是内容每天得推送,不可能一个小程序路径一个推送吧,因为小程序路径和项目路径不一致. 因为项目是用ThinkPHP开发的,在此附 ...
- IntelliJ IDEA自身以及maven项目打包方式
1. Idea自身打包方式 1.1 创建Artifacts 快捷键(Ctrl+Alt+Shift+S)打开项目的Project Structure.在Artifacts创建 接着,指定main cla ...
- oracle 将与本端(name)联系的人取出
本人与其他所有人认识的SQL: 首先新建测试表 create table DIM_IA_TEST6 ( NAME ), OTHERNAME ) ) 插入数据 --如果没有重复的记录,则不用去重使用un ...
- 讲解Flume
Spark Streaming通过push模式和pull模式两种模式来集成Flume push模式:Spark Streaming端会启动一个基于Avro Socket Server的Receiver ...
- 使用Quasar设计Material和IOS风格的响应式网站
使用Quasar设计Material和IOS风格的响应式网站 栏目: CSS · 发布时间: 8个月前 来源: segmentfault.com 本文转载自:https://segmentfaul ...
- 2019.12.11 java练习
class Demo01 { public static void main(String[] args) { //数组求最大值 int[] arr={1,2,3,4,5,6,7,8,9}; int ...
- MQTT 遗嘱使用
大部分人应该有这个需求: 我想让我的APP或者上位机或者网页一登录的时候获取设备的状态 在线还是离线 设备端只需要这样设置 注意:MQTT本身有遗嘱设置 所以大家可以设置遗嘱 ,注意哈,发布的主题 ...