LeetCode Crack Note --- 1. Two Sum
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
- 将原数组深拷贝一份,并进行排序,得到数组nums2;
- 使用两个指针,分别指向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
LeetCode Crack Note --- 1. Two Sum的更多相关文章
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- [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. ...
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)
Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...
- 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 ...
- [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 ...
- leetcode bugfree note
463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...
- 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 ...
- [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 ...
- [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 ...
随机推荐
- BZOJ3730 震波 【动态点分治】*
BZOJ3730 震波 Description 在一片土地上有N个城市,通过N-1条无向边互相连接,形成一棵树的结构,相邻两个城市的距离为1,其中第i个城市的价值为value[i]. 不幸的是,这片土 ...
- (IOCP)-C#高性能Socket服务器的实现
C#高性能Socket服务器的实现(IOCP) https://www.jianshu.com/p/c65c0eb59f22 引言 我一直在探寻一个高性能的Socket客户端代码.以前,我使用Sock ...
- flask第十九篇——模板【3】
请关注微信公众号:自动化测试实战 今天我们继续模板的知识,现在我们增加字典的复杂度,这个时候在render_template第二个参数可以传**title,以后我们会用**context代替原来的ti ...
- Sprint第一个冲刺(第四天)
一.Sprint介绍 今天我们完成了点餐界面及美化的任务,是通过TabActivity来实现的,界面可以进行滑动来进行点餐. 下面是实验截图: 任务进度: 二.Sprint周期 看板: 燃尽图:
- 【转】Linux动态链接(4)ldd与ldconfig
原文网址:http://tsecer.blog.163.com/blog/static/15018172012414105551345/ 一.动态链接工具ldd和ldconfig是动态链接的两个重要辅 ...
- centos6.6安装php5.3.3(2015/3/4)
问题:centos6.6因要升级mysql5.5所以yum重新更新了源,导致按照原来lamp环境安装步骤,安装php时一直找webtitic源,php5.3.24 而且一直无法安装下去 利用yum r ...
- CF 1093E Intersection of Permutations——CDQ分治
题目:http://codeforces.com/contest/1093/problem/E 只能想到转化成查询一个区间里值在一个范围里的数的个数…… 没有想到这样适合用主席树套树状数组维护.不过据 ...
- Errors running builder 'DeploymentBuilder' on project ' 解决方法
此问题一般发生在Myeclipse 保存文件并自动部署时候. Errors occurred during the build. Errors running builder 'DeploymentB ...
- jeecg中List页面标签的用法
1.t:datagrid的常用属性 1. <t:datagrid name="jeecgDemoList" checkbox="true" sortNam ...
- C/S模式与B/
网络程序开发的两种计算模式--C/S模式与B/S模式.两种各有千秋,用于不同场合. C/S适用于专人使用,安全性要求较高的系统: B/S适用于交互性比较频繁的场合,容易被人们所接受,倍受用户和软件开发 ...