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 ...
随机推荐
- Uncaught TypeError: Cannot read property 'decimalSeparator' of undefined
1.错误描述 jquery.jqGrid.min.js:477 Uncaught TypeError: Cannot read property 'decimalSeparator' of undef ...
- 机器学习算法实现解析——libFM之libFM的模型处理部分
本节主要介绍的是libFM源码分析的第三部分--libFM的模型处理. 3.1.libFM中FM模型的定义 libFM模型的定义过程中主要包括模型中参数的设置及其初始化,利用模型对样本进行预测.在li ...
- => 应用在js回调函数中
=> 可以简化以前的回调函数的调用,具体来说: 今后,几乎所有的回调函数都可用箭头函数简化 比如: 1. 所有回调函数都可: 去function改=> 2. 如果函数体只有一句话: 可省略 ...
- nmap 扫描工具
Nmap 7.30 ( https://nmap.org ) 使用方法: nmap [扫描类型(s)] [选项] {目标说明}目标说明:通过主机名称, IP 地址, 网段, 等等.协议: scanme ...
- ExpressionTree,Emit,反射
ExpressionTree,Emit,反射 https://www.cnblogs.com/7tiny/p/9861166.html [前言] 前几日心血来潮想研究着做一个Spring框架,自然地就 ...
- matlab的fda工具使用方法
MATLAB中用FDATool设计滤波器及使用 该文章讲述了MATLAB中用FDATool设计滤波器及使用. 1. 在Matlab中键入fdatool运行Filter Design and Analy ...
- gradle wrapper 简单使用
其实就是对于gradle 的一个包装,保证了项目版本的一致,同时减少配置 1. 生成wrapper // 使用gradle wrapper 命令 gradle wrapper 输出效果如下: [r ...
- database - 数据库设计/使用容易忽略的细节
一.设计 1,数据类型尽量使用数字型,数字型的比较比字符型的快很多 2,数据类型尽量小,预测可以满足未来需求的前提 3,尽量建表时字段不允许为null,除非必要,可以用NOT NULL+DEFAULT ...
- FastAdmin 社区 FAQ 帖子收集(F4NNIU 版 2018-08-12)
FastAdmin 社区 FAQ 帖子收集 为什么Selectpage下拉列表在编辑时总是返回第一行的值? https://forum.fastadmin.net/thread/2399 根据条件值判 ...
- 获取sonar扫描结果
api通过抓包获取 java 1.get和post方法 package com.tools.httpUtil; import java.io.BufferedReader; import java.i ...