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 ...
随机推荐
- Windows手动安装Apache,MySql服务
绿色版的Apache,Mysql需要以服务方式运行.或者由于某种原因服务管理器里面没有服务项了,可以进行手工注册服务和启并服务. # Apache Apache进到安装目录的bin目录下,运行dos命 ...
- (三十八)js之柯里化
先给大家介绍什么是柯里化与反柯里化 百度翻译: 在计算机科学中,柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的 ...
- BJOI2019 游记
BJOI 2019 游记 Day 1 开场拿到 \(T1\) 发现可以转成求平均 \(log\) 直接 \(AC\) 自动机上 \(Dp\) 一波即可 \(T2\) 发现是到数论神仙题,大概能想到要用 ...
- MySQL免安装版安装配置、修改密码
一:MySQL的下载安装 1.1 下载 我下载的是 ZIP Archive 版的,win7 64位的机器支持使用,而且相对而言,简单.干净. 首先,进入MySQL的官方网址,依次点击Downloads ...
- 互联网公司面试必问的mysql题目(上)
又到了招聘的旺季,被要求准备些社招.校招的题库.(如果你是应届生,尤其是东北的某大学,绝对福利哦) 介绍:MySQL是一个关系型数据库管理系统,目前属于 Oracle 旗下产品.虽然单机性能比不上or ...
- net core集成CAP
net core集成CAP https://www.cnblogs.com/guolianyu/p/9756941.html 一.前言 感谢杨晓东大佬为社区贡献的CAP开源项目,传送门在此:.NET ...
- spring Bean配置的三种形式
Spring Bean配置有以下三种形式: 传统的xml配置 Spring 2.5 以后新增注解配置 Spring3.0以后新增JavaConfig 1. 传统的xml配置 <?xml vers ...
- sublime text 3设置浏览器快捷键
一.设置默认浏览器 1,打开sublime 依次选择 tools > build system > new build system... 2,选择你喜欢的浏览器,右键 > 属性 把 ...
- elasticsearch snapshot快照备份和恢复
环境:mac 使用brew 安装elasticsearch 1.在 /usr/local/etc/elasticsearch/elasticsearch.yml 文件中配置快照地址 p ...
- excel oracle字段命名(大写下划线分词)转 驼峰命名
干货: (帕斯卡) =LEFT(C251,1)&MID(SUBSTITUTE(PROPER(C251),"_",""),2,100) (驼峰) =LOW ...