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 ...
随机推荐
- C++中const指针用法汇总
这里以int类型为例,进行说明,在C++中const是类型修饰符: int a; 定义一个普通的int类型变量a,可对此变量的值进行修改. const int a = 3;与 int const a ...
- [置顶]
【机器学习PAI实践六】金融贷款发放预测
一.背景 很多农民因为缺乏资金,在每年耕种前会向相关机构申请贷款来购买种地需要的物资,等丰收之后偿还.农业贷款发放问题是一个典型的数据挖掘问题.贷款发放人通过往年的数据,包括贷款人的年收入.种植的作物 ...
- (一)mvc与mvvm设计模式
前沿:了解设计模式对我们而言,具有很大意义,对语言没有限制,它适用于任何语言,是一种变成思想.设计模式最初有四人帮提出,有兴趣的同学可以去了解下,今天给大家主要分析mvc与mvvm设计模式 一.mvc ...
- Linq:Grouping Operators
[Category("Grouping Operators")] [Description("This sample uses group by to partition ...
- UVA11174 Stand in a Line
题意 PDF 分析 \[ f(i)=f(c_1)f(c_2)\dots\times(s(i)-1)!/(s(c_1)!s(c_2)! \dots s(c_k)! )\\ f(root)=(s(root ...
- WPF 自定义BarChartControl(可左右滑动的柱状图)(转)
自定义可左右滑动.拖拽滑动的平面柱状图 在做这种样式控件之前,可先浏览我之前预研的控件: A.自定义左右滑动ScrollViewer(可拖动滑动) B.自定义Bar柱状图 OK,现在说下控件具体设计过 ...
- mybatis返回Date类型数据 格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") public Date getC ...
- Linux增加Swap分区
Linux增加Swap分区 dd if=/dev/zero of=/data/swap/swapfile1 bs=4096 count=2097152 mkswap /data/swap/swapfi ...
- sqlbulkcopy 使用DataTable作为数据源的数据类型问题--来自数据源的String类型的给定值不能转换为指定目标列的类型 uniqueidentifier
今天做批量插入的时候,SQLSERVER总是报错,错误提示“来自数据源的String类型的给定值不能转换为指定目标列的类型 uniqueidentifier”. 首先核对了一下定义的dataTable ...
- DHCP(一)
DHCP(Dynamic Host Configuration Protocol,动态主机配置协议)是一个局域网的网络协议,使用UDP协议工作, 主要有两个用途:给内部网络或网络服务供应商自动分配IP ...