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的更多相关文章

  1. 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 ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [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 ...

  6. [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 ...

  7. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  8. [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 ...

  9. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  10. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. 首个threejs项目-前端填坑指南

    第一次使用threejs到实际项目中,开始的时候心情有点小激动,毕竟是第一次嘛,然而做着做着就感受到这玩意水好深,满满的都是坑,填都填不过来.经过老板20天惨无人道的摧残,终于小有成就. 因为第一次搞 ...

  2. json与JavaScript对象互换

    1,json字符串转化为JavaScript对象: 方法:JSON.parse(string) eg:var account = '{"name":"jaytan&quo ...

  3. MSDN文档篇

    很多人网上下载3~10G不等的MSDN文档,发现,下载完成了不会用 很多人每次都得在线下载文档,手上万千PC,都重新下载不是得疯了? so==> 先看几张图 推荐一个工具:https://vsh ...

  4. iOS系列文章

    本博客全为原创,如果借鉴了其他文章会在博文的下面进行说明.欢迎转载,但要在文章中给出原文链接,谢谢. 有链接的说明已经发布,没有链接的说明还没有发布. 并不是所有的博文都在这里罗列,有兴趣的可以看博客 ...

  5. [WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform

    eclipse maven clean install 报错 1. 修改properties-->resource-->utf-8仍然报错 2.修改项目pom.xml文件,增加: < ...

  6. LINQ to SQL Select查询

    1. 查询所有字段 using (NorthwindEntities context = new NorthwindEntities()) { var order = from n in contex ...

  7. 中国CIO最关心的八大问题(下)

    中国CIO最关心的八大问题(下) 从调研数据还可以看出,在企业级IT建设与投资上,CIO们并非是一群狂热的技术信徒,他们更多的是从企业发展阶段.信息化程度.技术成熟度.ROI等方面进行综合评估. 五. ...

  8. MySQL全文索引 FULLTEXT索引和like的区别

    1.概要 InnoDB引擎对FULLTEXT索引的支持是MySQL5.6新引入的特性,之前只有MyISAM引擎支持FULLTEXT索引.对于FULLTEXT索引的内容可以使用MATCH()-AGAIN ...

  9. 清除打印机队列中无法清除的任务 & 清空打印池

    故障现象典型表现为以下两种情况 1.当打印任务开始进行时,这些打印任务便被保存在打印作业列表(也称打印队列)内.如果打印机因意外暂停(如打印机未连接)而未完成打印任务,则该打印任务将列入打印队列,并且 ...

  10. excel常用技巧

    复制表格时,如果要加上行标和列标.页面布局->工作表选项:标题,勾上打印->复制下拉框->复制为图片加上打印样式 一行长拆成几行短或几行短变成一行长的文本拆分,可以通过:填充-> ...