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 ...
随机推荐
- 人生苦短之我用Python篇(深浅拷贝、常用模块、内置函数)
深浅拷贝 有时候,尤其是当你在处理可变对象时,你可能想要复制一个对象,然后对其做出一些改变而不希望影响原来的对象.这就是Python的copy所发挥作用的地方. 定义了当对你的类的实例调用copy.c ...
- [QT][问题记录]发布软件时遇到的问题
2017-3-9 11:22:13 无法定位程序输入点 _ZdaPvj 于动态链接库 libstdc++-6.dll 上. 这是在自己机器上出现的问题. 使用cmd 进行命令 windeployqt ...
- 我所常用的git命令
说明公司向用git来管理项目的代码,我以前只是在eclipse中使用菜单来操作git,现在,学习一下命令,这样也不用安装各种git客户端软件了.git安装在官网上下载git,安装完成之后,在命令行中输 ...
- BZOJ - 2957 (分块/线段树)
题目链接 本质是维护斜率递增序列. 用分块的方法就是把序列分成sqrt(n)块,每个块分别用一个vector维护递增序列.查询的时候遍历所有的块,同时维护当前最大斜率,二分找到每个块中比当前最大斜率大 ...
- Scrapy框架及组件描述
Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非 ...
- 剑指offer—第二章算法之快速排序
算法:排序和查找(二分查找,归并排序,快速排序),位运算等. 查找:顺序查找,哈希查找,二叉排序树查找,哈希表. 二分查找可以解决:"旋转数组中的最小数字","数字在排序 ...
- IQ信号理解
可参考http://wenku.baidu.com/link?url=Y3plyK9lgl96QowljJkWhgVaUGbH11j178DkId_vcl9z1V5cjl9ycTiB4Ym4iaypL ...
- jenkins 重置密码
说明 最近在折腾jenkins,配置用户权限时点错了,选择了安全矩阵后没有添加用户,就保存配置了,然后就报错了,提示没有Overall/Read权限.还有另外一个问题,用户的密码忘记了怎么办? 一 ...
- FastAdmin Bootstrap-Table 分页列表 pageList 如何设置?
FastAdmin Bootstrap-Table 分页列表 pageList 如何设置? FastAdmin 的 表格使用的是 Bootstrap-Table 组件,这个组件该有的功能他都有. 默认 ...
- BZOJ4755:[JSOI2016]扭动的回文串
浅谈\(Manacher\):https://www.cnblogs.com/AKMer/p/10431603.html 题目传送门:https://lydsy.com/JudgeOnline/pro ...