LeetCode-01 两数之和(Two Sum)
题目描述
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,
你可以假设每个输入只对应一个答案,且同样的元素不能被重复利用。
示例
给定数组 nums = [2, 7, 11, 15], target = 9,
因为 nums[0] + nums[1] = 2 + 7 =9,
所以返回结果 [0, 1]。
分析过程:
初看题目,首先想到两次循环暴力匹配。遍历数组 nums 查找是否有满足 target-nums[i]的元素。显然时间复杂度为 O(n^2),空间复杂度为 O(1)。
实现
C#
public class Solution {
public static int[] TwoSum(int[] nums, int target)
{
int[] res = new int[2];
int len = nums.Length;
for (int i = 0; i < len; i++)
{
int numberToFind = target - nums[i];
for (int j = i + 1; j < len; j++)
{
if(nums[j] == numberToFind)
{
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
}
其实细想,我们只需要遍历一次数组,将然后根据 target-nums[i]为 key 在 HashTable 中查找是否有与之匹配的 value,如果有则说明找到了目标,并将当前索引和 hashtable 中的 value 返回;没有则将当前值作为 key,当前索引作为 value 存入 hashtable 中。
因为 hashtable 的查询平均时间复杂度为 O(1),所以我们的算法时间复杂度从 O(n^2)降到 O(n),因为引入了一个额外的 hashtable 存储,并且最坏情况需要将整个数组的数据放入,所以空间复杂度为 O(n)。
C#
public class Solution {
public int[] TwoSum(int[] nums, int target)
{
int[] res = new int[2];
Dictionary<int,int> dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
if(dic.TryGetValue(target - nums[i], out int value)) // O(1)
{
res[1] = i;
res[0] = value;
break;
}
if (!dic.ContainsKey(nums[i])) // O(1)
{
dic.Add(nums[i], i);
}
}
return res;
}
}
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int size = nums.size();
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < size; i++) {
int numberToFind = target - nums[i];
if (hash.contains(numberToFind)) {
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
hash[nums[i]] = i;
}
return result;
}
};
Python
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
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
Rust
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hash = HashMap::new();
for (index, value) in nums.iter().enumerate() {
let number_to_find = target - *value;
if hash.contains_key(&number_to_find) {
return vec![hash[&number_to_find], index as i32];
}
hash.insert(value, index as i32);
}
return vec![];
}
}
Javascript
var twoSum = function (nums, target) {
var hash = {};
for (let i = 0; i < nums.length; i++) {
let index = hash[target - nums[i]];
if (typeof index !== "undefined") {
return [index, i];
}
hash[nums[i]] = i;
}
return null;
};
Typescript
function twoSum(nums: number[], target: number): number[] {
let res: number[] = [0, 0];
let dic: Map<number, number> = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
if (dic.has(target - nums[i])) {
res[0] = dic.get(target - nums[i]) as number;
res[1] = i;
return res;
} else {
dic.set(nums[i], i);
}
}
return [];
}
Go
// 1.Two Sum
func twoSum(nums []int, target int) []int {
hashTable := map[int]int{}
for i, x := range nums {
if p, ok := hashTable[target-x]; ok {
return []int{p, i}
}
hashTable[x] = i
}
return nil
}
Java
public class Solution {
/**
* 1. Two Sum
*
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (map.containsKey(target - nums[i])) {
res[1] = i;
res[0] = map.get(target - nums[i]);
break;
}
if (!map.containsKey(nums[i])) {
map.put(nums[i], i);
}
}
return res;
}
}
引用
习题来自LeetCode中国
所有代码均可以在Github获取
LeetCode-01 两数之和(Two Sum)的更多相关文章
- 每天一道面试题LeetCode 01 -- 两数之和
Two Sum 两数之和 Given an array of integers, find two numbers such that they add up to a specific target ...
- LeetCode 01 两数之和
链接:https://leetcode-cn.com/problems/two-sum 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们 ...
- LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)
653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...
- LeetCode:两数之和、三数之和、四数之和
LeetCode:两数之和.三数之和.四数之和 多数之和问题,利用哈希集合减少时间复杂度以及多指针收缩窗口的巧妙解法 No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在 ...
- 领扣-1/167 两数之和 Two Sum MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- 前端与算法 leetcode 1. 两数之和
目录 # 前端与算法 leetcode 1. 两数之和 题目描述 概要 提示 解析 解法一:暴力法 解法二:HashMap法 算法 传入[1, 2], [11, 1, 2, 3, 2]的运行结果 执行 ...
- LeetCode刷题 - (01)两数之和
题目描述 给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元 ...
- Leetcode 001. 两数之和(扩展)
1.题目要求 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 2.解法一:暴力法(for*for,O(n*n)) ...
- leetCode:twoSum 两数之和 【JAVA实现】
LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...
- 【Leetcode】两数之和,三数之和,四数之和
两数之和 题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这 ...
随机推荐
- 一篇带你了解如何使用纯前端类Excel表格构建现金流量表
现金流量表(Cash Flow Statement),是指反映企业在一定会计期间现金和现金等价物流入和流出的报表.现金流量表是企业财务报表的三个基本报告之一(另外两个是资产负债表和损益表). 为了全面 ...
- Hudi 数据湖的插入,更新,查询,分析操作示例
Hudi 数据湖的插入,更新,查询,分析操作示例 作者:Grey 原文地址: 博客园:Hudi 数据湖的插入,更新,查询,分析操作示例 CSDN:Hudi 数据湖的插入,更新,查询,分析操作示例 前置 ...
- DevOps|1024程序员节怎么做?介绍下我的思路
1024,祝每个程序员小哥哥小姐姐节日快乐. 因为在研发效能部门,我支持过几次 1024 程序员节的活动,所以经常有朋友问我1024 程序员节怎么做,本篇就是简单介绍下我的思路,希望对你有用. 102 ...
- 2.-url和视图函数
一.URL-结构 1.定义:统一资源定位符 Uniform Resource Locator 2.作用:用来表示互联网上某个资源地址 3.URL的一般语法格式为(注:[]代码其中的内容可以省略): 格 ...
- 基于.NetCore开发博客项目 StarBlog - (19) Markdown渲染方案探索
前言 笔者认为,一个博客网站,最核心的是阅读体验. 在开发StarBlog的过程中,最耗时的恰恰也是文章的展示部分功能. 最开始还没研究出来如何很好的使用后端渲染,所以只能先用Editor.md组件做 ...
- The XOR Largest Pair(字典树)
题目描述 在给定的 N 个整数 A1,A2,-,AN 中选出两个进行异或运算,得到的结果最大是多少? 输入格式 第一行一个整数 N. 第二行 N 个整数 Ai. 输出格式 一个整数表示答案. 样例 ...
- k8s挂在问题
今天在重启pod这个后发现一直处于 然后去describe发现报错如下 先去手动mount的发现挂在不了 然后去slave节点发现这个没有安装 然后手动去安装后重启pod问题解决
- PCA降维的原理及实现
PCA可以将数据从原来的向量空间映射到新的空间中.由于每次选择的都是方差最大的方向,所以往往经过前几个维度的划分后,之后的数据排列都非常紧密了, 我们可以舍弃这些维度从而实现降维 原理 内积 两个向量 ...
- Java多线程-线程关键字(二)
Java中和线程相关的关键字就两:volatile和synchronized. volatile以前用得较少,以后会用得更少(后面解释).它是一种非常轻量级的同步机制,它的三大特性是: 1.保证可见性 ...
- RHCE习题
RHCE习题 考试说明: RH294系统信息 在练习期间,您将操作下列虚拟系统: 真实机: foundation: kiosk:redhat root: Asimov workstation.lab. ...