LeetCode - Two Sum
Two Sum 題目連結
官網題目說明:
解法:
從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出。
/// <summary>
/// 暴力解O(n2)
/// </summary>
/// <param name="nums"></param>
/// <param name="target"></param>
/// <returns></returns>
public static int[] TwoSum(int[] nums, int target)
{
int[] result = new int[];
for (int i = ; i < nums.Length; i++)
{
for (int j = i + ; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
result[] = i;
result[] = j;
break;
}
}
} return result;
}
另題目內有討論時間複雜度表現較為優秀的解法,也一併實作看看。
此為兩步驟(two pass)hashtable,先將給定值放入hashtable(此用dictionary,圴為key/value的組合),但有可能會找到自已
/// <summary>
/// two pass hashtable 解, O(1),如果有碰撞(collision)則為O(n)
/// 因為先把所有數放進hashtable,有可能找到自已
/// </summary>
/// <param name="nums"></param>
/// <param name="target"></param>
/// <returns></returns>
public static int[] TwoSum2(int[] nums, int target)
{
Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = ; i < nums.Length; i++)
{
map[nums[i]] = i;
} for (int i = ; i < nums.Length; i++)
{
//餘數
int complement = target - nums[i]; if (map.ContainsKey(complement) && map[complement] != i)
{
//當前數的index & 餘數的index
return new int[] { i, map[complement] };
}
} throw new ArgumentNullException();
}
此為one pass hashtable,最大特點在先找再放值,考慮迴圈的情形下
i == 0,hashtable內無值
i == 1,找的是hash[0]
i == 2,找的是 hash[0] hash[1]
i == n,找的是hash[0]..hash[n - 1]
不會有碰撞的情形
/// <summary>
/// one pass hashtable
/// hashtable內永遠只有 nums[i-1],nums[i-2]...的數,不會找到自已
/// </summary>
/// <param name="nums"></param>
/// <param name="target"></param>
/// <returns></returns>
public static int[] TwoSum3(int[] nums, int target)
{
Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = ; i < nums.Length; i++)
{
int complement = target - nums[i];
if (map.ContainsKey(complement))
{
return new int[] { map[complement], i };
} map[nums[i]] = i;
} throw new ArgumentException();
}
個人的練習與紀錄,歡迎大家討論與指教
LeetCode - Two Sum的更多相关文章
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
- 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)
剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...
- [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...
- [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...
- [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [LeetCode] Combination Sum III 组合之和之三
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
随机推荐
- java中的字符串相关知识整理
字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...
- Jexus 5.8.2 正式发布为Asp.Net Core进入生产环境提供平台支持
Jexus 是一款运行于 Linux 平台,以支持 ASP.NET.PHP 为特色的集高安全性和高性能为一体的 WEB 服务器和反向代理服务器.最新版 5.8.2 已经发布,有如下更新: 1,现在大 ...
- 使用Visual Studio 2015 开发ASP.NET MVC 5 项目部署到Mono/Jexus
最新的Mono 4.4已经支持运行asp.net mvc5项目,有的同学听了这句话就兴高采烈的拿起Visual Studio 2015创建了一个mvc 5的项目,然后部署到Mono上,浏览下发现一堆错 ...
- UML课程复习重点
第一章 一.UML图示建模工具 二.UML--统一建模语言,以图形符号为基础,描述软件模型既简洁又清晰.它不是开发方法,是独立于任何开发方法之外的语言.它用于描述软件系统分析.设计和实施中的各种模型. ...
- Git初探--笔记整理和Git命令详解
几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...
- Unity3D框架插件uFrame实践记录(一)
1.概览 uFrame是提供给Unity3D开发者使用的一个框架插件,它本身模仿了MVVM这种架构模式(事实上并不包含Model部分,且多出了Controller部分).因为用于Unity3D,所以它 ...
- ASP.NET Core 中文文档 第四章 MVC(4.2)控制器操作的路由
原文:Routing to Controller Actions 作者:Ryan Nowak.Rick Anderson 翻译:娄宇(Lyrics) 校对:何镇汐.姚阿勇(Dr.Yao) ASP.NE ...
- sql server 取文件名函数 转载
/****** Object: UserDefinedFunction [dbo].[GetDirectoryPath] Script Date: 2016-12-16 16:54:05 ****** ...
- keepalive的不足,如何处理
MySQL(或者其它服务)的keepalived高可用监控脚本 开发脚本需求:我们知道,keepalive是基于虚拟ip的存活来判断是否抢占master的机制的,但是如果我们做了MySQL的keepa ...
- PHP相关代码
1 <html> <head> <meta http-equiv="content-type" content="text/h ...