Discription

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

Difficulty:

Solving Strategy

  1. 将原数组深拷贝一份,并进行排序,得到数组nums2;
  2. 使用两个指针,分别指向nums2的首尾,两个指针同时向中间移动,并判断当前下标对应元素的和是否等于target。(这点在特定情况下,可以节省大量时间,eg. nums=[0,1,2,3,…,9999],target=1000)

My Solution

 # Use Python3
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int:rtype: List[int]
""" nums2 = nums[:] # Copy a new list for sorting
nums2.sort()
ii = 0
count = nums.__len__()
jj = count-1 val1 = 0
val2 = 0
while ii < jj:
if nums2[ii] + nums2[jj] == target:
val1 = nums2[ii]
val2 = nums2[jj]
break
elif nums2[ii] + nums2[jj] < target:
ii = ii + 1
elif nums2[ii] + nums2[jj] > target:
jj = jj - 1 indexList = []
for i in range(count):
if nums[i] == val1:
indexList.append(i)
break for j in range(count-1, -1, -1):
if nums[j] == val2:
indexList.append(j)
break indexList.sort()
return [indexList[0], indexList[1]]

Runtime: 85 ms

Official Solution

Approach #1 (Brute Force) [Accepted]

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target - x.

 public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}

Complexity Analysis:

  • Time complexity : O(n). We traverse the list containing n elements exactly twice. Since the hash table reduces the look up time to O(1), the time complexity is O(n).
  • Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly n elements.

Approach #2 (Two-pass Hash Table) [Accepted]

Approach #3 (One-pass Hash Table) [Accepted]

Reference

[南郭子綦's blog]

 

LeetCode Crack Note --- 1. Two Sum的更多相关文章

  1. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  2. [leetcode]364. Nested List Weight Sum II嵌套列表加权和II

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  3. Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)

    Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...

  4. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  5. [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

  6. leetcode bugfree note

    463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...

  7. leetcode@ [327] Count of Range Sum (Binary Search)

    https://leetcode.com/problems/count-of-range-sum/ Given an integer array nums, return the number of ...

  8. [LeetCode] Partition to K Equal Sum Subsets 分割K个等和的子集

    Given an array of integers nums and a positive integer k, find whether it's possible to divide this ...

  9. [LeetCode] Split Array with Equal Sum 分割数组成和相同的子数组

    Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies fol ...

随机推荐

  1. Typescript : 遍历Array的方法:for, forEach, every等

    方法一,for…of 这个貌似是最常用的方法,angular 2中HTML语法绑定也是要的这种语法. let someArray = [1, "string", false]; f ...

  2. 阿里云ECS 环境是CentOS 7.3安装mongodb3

    CentOS安装mongodb https://www.cnblogs.com/zddzz/p/10069912.html CentOS安装mongodb 我的是阿里云ECS 环境是CentOS 7. ...

  3. C#连接数据库以及增、删、改、查操作

    using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; usin ...

  4. wpf中如何在xaml中绑定cs中类的属性

    cs代码:/// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWin ...

  5. pid参数调节的几句话

    如果参数上升太快,降低Kp值,如果震荡太剧烈(振荡幅度过大),降低Ki值,如果曲线震荡部分上升下降太快则尝试调整Kd值.

  6. 借助CustomBehaviorsLibrary.dll写出水印效果(转)

    在项目中载入这个dll 之后引用 使用方法具体如下图: 在这里需要注意到是项目中对interactivity的引用 :       好文要顶 关注我 收藏该文  

  7. UI异常

    为什么chaneTab调用后,这个Tab都消失了? 因为li和table都用同一个ID所以,其中有一个步骤是清空表:$("#XXid").remove,连带着把那个li(tab)也 ...

  8. 浅谈Trie

    所谓\(Trie\)就是字典树. 何为字典树?想象一下我们平时用拼音查字法在字典树查汉字的时候,一位一位确定这个汉字的拼音从而翻到我们想要看的那一面. 所以\(Trie\)树跟字典一样,是一种逐位检索 ...

  9. linux CentOS 安装rz和sz命令 lrzsz

    lrzsz在linux里可代替ftp上传和下载. lrzsz 官网入口:http://freecode.com/projects/lrzsz/ lrzsz是一个unix通信套件提供的X,Y,和ZMod ...

  10. Linux和Windows的遍历目录下所有文件的方法对比

    首先两者读取所有文件的方法都是采用迭代的方式,首先用函数A的返回值判断目录下是否有文件,然后返回值合法则在循环中用函数B直到函数B的返回值不合法为止.最后用函数C释放资源. 1.打开目录 #inclu ...