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. 关于ehcache缓存的使用(简单对比redis)

    前言 最近在做一个项目,某个接口查询数据到返回数据总计需要7000+毫秒,一直在考虑优化的问题,优化也有原来的一家一家查询到一次查询所有的,在查询不同天数.结果是1500+,虽然优化了不少,但是数据结 ...

  2. 如何使用 MSBuild Target(Exec)中的控制台输出

    我曾经写过一篇文章 如何创建一个基于命令行工具的跨平台的 NuGet 工具包,通过编写一个控制台程序来参与编译过程.但是,相比于 基于 Task 的方式,可控制的因素还是太少了. 有没有什么办法能够让 ...

  3. python 客户端点对点通信小案例

    点对点通讯分为客户端和服务器,多个客户端通过服务器进行信息的交流 服务器端代码  service端 #!/usr/bin/env python # -*- coding:utf-8 -*- impor ...

  4. oracle 之 手动建库

    1.-- 查看服务器 ORA 环境变量情况[oracle@orastb ~]$ env|grep ORAORACLE_BASE=/u01/app/oracleORACLE_HOME=/u01/app/ ...

  5. git 获取远程分支

    另一哥们将分支push到库中,我怎么获取到他的分支信息呢? 如果安装了git客户端,直接选择fetch一下,就可以获取到了. 如果用命令行,运行 git fetch,可以将远程分支信息获取到本地,再运 ...

  6. 浅谈splay

    \(BST\) 二叉查找树,首先它是一颗二叉树,其次它里面每个点都满足以该点左儿子为根的子树里结点的值都小于自己的值,以该点右儿子为根的子树里结点的值都大于自己的值.如果不进行修改,每次查询都是\(O ...

  7. 各大互联网公司2014前端笔试面试题–HTML,CSS篇

    Html篇: 1.你做的页面在哪些流览器测试过?这些浏览器的内核分别是什么? IE: trident内核 Firefox:gecko内核 Safari:webkit内核 Opera:以前是presto ...

  8. elastic search6.2.2 实现用户搜索记录查询(去重、排序)

    elastic search6.2.2 实现搜索记录查询 ,类似新浪微博这种,同样的搜索记录后面时间点的会覆盖前面的(主要思路:关键词去重,然后按时间排序) 先创建索引 //我的搜索 PUT my_s ...

  9. Python Socke

    回射 SERVER #!/usr/bin/python3 #_*_ coding:utf- _*_ import socket,os,time import socketserver import t ...

  10. java代码---数据类型的强制转换----不懂啊

    总结:看写的测试代码 字符到整型必须进行强制转换 package com.a.b; //byte→int 可以 int范围大,不必转换 B.short→long //C.float→double 这个 ...