Leetcode:Two Sum分析和实现
问题表示提供一个整数数组nums,以及一个目标target,要找到两个下标i与j,使得nums[i] + nums[j] = target。
最简单的思路是两次循环:
for a in nums
for b in nums
if a + b = target then
return [a.index, b.index]
这样的代码的时间复杂度是O(n^2),其中n表示nums的长度。当n为1e4时,执行时间高达?e8,其中?是一个有上界的数值。
可以利用排序和二分查找优化这一过程:
sort(nums)
for a in nums
b = target - a
bIndex = binarySearch(nums, b)
if bIndex >= 0 then
return [a.index, bIndex]
这样代码的时间复杂度为排序时间复杂度+nx二分查找时间复杂度,这里采用归并排序来排序,因此结果为O(nlogn)+nxO(logn)=O(nlogn)。当n为1e4时,执行时间为?e5左右,其中?是一个有上界的数值。
最后贴上Java的完整实现代码给有需要的人:
package cn.dalt.leetcode;
import java.util.Arrays;
import java.util.Comparator;
public class TwoSum {
public static void main(String[] arg) {
System.out.println(Arrays.toString(
new TwoSum().twoSum(new int[]{3, 3}, 6)
));
}
static class Element {
final int num;
final int index;
public Element(int num, int index) {
this.num = num;
this.index = index;
}
@Override
public int hashCode() {
return num;
}
@Override
public boolean equals(Object obj) {
return num == ((Element) obj).num;
}
}
static final Comparator<Element> ELEMENT_COMPARATOR = new Comparator<Element>() {
@Override
public int compare(Element o1, Element o2) {
return o1.num > o2.num ? 1 : o1.num < o2.num ? -1 : 0;
}
};
public int[] twoSum(int[] nums, int target) {
Element[] elements = new Element[nums.length];
for (int i = 0, bound = nums.length; i < bound; i++) {
elements[i] = new Element(nums[i], i);
}
//Sort the array with ascending order
Arrays.sort(elements, ELEMENT_COMPARATOR);
//Quickly find solution with binarysearch
for (int i = 0, bound = elements.length; i < bound; i++) {
Element a = elements[i];
Element b = new Element(target - a.num, -1);
if (a.num == b.num) {
if (i < elements.length - 1 && elements[i + 1].num == a.num) {
return new int[]{a.index, elements[i + 1].index};
}
}
int bindex = Arrays.binarySearch(elements, b, ELEMENT_COMPARATOR);
if (bindex >= 0) {
return new int[]{a.index, elements[bindex].index};
}
}
return null;
}
}
Leetcode:Two Sum分析和实现的更多相关文章
- 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)
剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...
- 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 ...
- [LeetCode] 907. Sum of Subarray Minimums 子数组最小值之和
Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarra ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- [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 ...
- [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 ...
- [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [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 ...
随机推荐
- Java局域网对战游戏、天气预报项目
功能 1.天气预报 2.局域网对战 展示 java学习群669823128 部分源码 package game.weather; import java.util.HashMap; public ...
- Microsoft Office Visio 2013 (安装 + 激活)
Visio是一款能处理复杂信息.系统和流程进行可视化.分析和交流的软件,从“office 2003”以后,Visio作为一个单独软件发行,不再集成于office办公软件. 工具/原料 Visio 电脑 ...
- 《DSP using MATLAB》示例Example7.15
代码: %T1 = 0.5 M = 40; alpha = (M-1)/2; l = 0:M-1; wl = (2*pi/M)*l; Hrs = [ones(1, 5), 0.5, zeros(1, ...
- GIT多人合作开发
. 建立代码仓库(专门用于团队开发的代码仓库) ============================================================================ ...
- 为什么 FastAdmin 的插件不全部免费?
为什么 FastAdmin 的插件不全部免费? 主要还是有以下几个原因. 支持开发者. 为了支付网站空间费和 CDN 费. 有收入后可以更好的开发 FastAdmin.
- 支付宝RSA签名
1.参考网上相关文章,开放php中的openssl,但使用网上例子调用openssl_pkey_new,一直报100013错误.后改用用支付宝提供的SDKdemo程序 发现使用提供的privkye,可 ...
- (转)setTextColor()的参数设置方式
setTextColor()的参数设置方式 分类: Android界面研究2011-12-09 23:27 11160人阅读 评论(2) 收藏 举报 查了下资料发现setTextColor()的参数应 ...
- 发现一个github的奇葩设定
commit时留下的邮箱,会显示在github的提交记录里,然后居然自动找服务器上的这个邮箱注册的人,显示这个用户名.
- 1、python基础速成
基础模块 def prt(age,name):#函数定义 print("%s is %d 年龄 old"%(name,age)) if __name__=="__main ...
- eclipse-连接TFS错误 <the server to respond with a valid http response>解决方法
解决办法 如果普通凭证有多个,则将普通凭证给删除.