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. selenium python实例脚本1

    #!/usr/local/bin/python3 # coding=utf-8 #统一编码from selenium import webdriverfrom time import sleep#im ...

  2. 使用poi进行excel导入并解析插入数据库

    前言 最近还得写excel的导入导出,结果还是得百度,虽然都能看懂,但是还是想记录下来这些东西 正文 1. 导入jar包 <dependency> <groupId>org.a ...

  3. ssm异常;

    问题:Invalid bound statement (not found): com.itq.mapper.TbItemMapper.selectByExample 解决:修改pom.xml文件中添 ...

  4. {Reship}{Socket}C#简单应用

    This article come frome here ======================================================================= ...

  5. Linux之 xstart调用 x11vnc远程图形化桌面

    问题:用 xmanager 中的 xstart 启动界面,报x11无法打开 . 1. root调整x11参数,将其打开[root@localhost ~]# vi /etc/ssh/sshd_conf ...

  6. python-生成测试报告-然后自动发送邮件

    前两篇单独介绍了生成测试报告和自动发送邮件,那么现在把两者整合到一起:生成测试报告后然后自动发送邮件,这里只是简单的整合实现功能,其实还可以优化的,先用吧,后面再慢慢优化 先看下目录,其实目录还是一样 ...

  7. 关于tab的切换之共用html页面,而引发的页面跳转错乱问题

    在一个项目中的同一个模块中,有多个tab(并且多个tab对应的页面结构完全一样),tab的每次切换,不同tab调用不同的接口,利用一个switch进行判断,根据当前的类型去调用不同的接口,返回不同数据 ...

  8. Android screencap截屏指令

    查看帮助(注意:有的网友错误使用 screencap -v ,结果差不多,因为系统不能识别-v,就自动打印出帮助信息) # screencap -hscreencap -husage: screenc ...

  9. c#实现QQ群成员列表导出及邮件群发之群列表及群成员获取

    主题已迁移至:http://atiblogs.com/ ITO-神奇的程序员

  10. python 生成器和生成器表达式

    1.生成器 生成器的本质就是迭代器 生成器的特点和迭代器一样.取值方式和迭代器一样(__next__(),send():给上一个yield传值) 生成器一般由生成器函数或者生成器表达式来创建 其实就是 ...