问题表示提供一个整数数组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分析和实现的更多相关文章

  1. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  2. 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 ...

  3. [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 ...

  4. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  5. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  6. [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 ...

  7. [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 ...

  8. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  9. [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 ...

随机推荐

  1. 学习nodejs部分基础内容入门小结

    Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. Node.js 的包管理器 n ...

  2. bisect模块用于插入

    参考链接: chttp://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html水

  3. Angular2配置文件详解

    初学接触Angular2的时候,通过ng new your-project-name 命令生成一个工程空壳,本文来介绍下每个文件的作用及含义. 先来看看src的文件目录: 文件详解 File 文件 P ...

  4. jquery中ajax异步调用接口

    之前写过一个原始的.无封装的页面,没有引入任何外部js,直接实例化Ajax的XmlRequest对象去异步调用接口,参见Ajax异步调用http接口后刷新页面,可对比一下. 现在我们用jquery包装 ...

  5. linux下用户和组相关的文件及相关管理命令

    1.用户信息文件  /etc/passwd 示例root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2: ...

  6. Redis数据清除问题

    Redis中数据清除可以分为两种方式 手动清除:指定要清除的key,通过delete命令即可清除 自动清除:使用Redis提供的数据过期策略 Redis数据过期策略      redis提供了非常灵活 ...

  7. The java.util.concurrent Synchronizer Framework笔记

    这篇笔记是关于 Doug Lea 的 The java.util.concurrent Synchronizer Framework . 原文地址:http://gee.cs.oswego.edu/d ...

  8. MongoDB Data Model 浅谈

    MongoDB 对于数据的 schema 要求很灵活. 与 MySQL 相比,collection 并不会强制文档的结构.(MySQL 在定义表时, 需要指定有哪些字段.类型.展示长度等) 因此,插入 ...

  9. 微服务监控之二:Metrics+influxdb+grafana构建监控平台

    系统开发到一定的阶段,线上的机器越来越多,就需要一些监控了,除了服务器的监控,业务方面也需要一些监控服务.Metrics作为一款监控指标的度量类库,提供了许多工具帮助开发者来完成自定义的监控工作. 使 ...

  10. juc原子类之五:AtomicLongFieldUpdater原子类

    概要 AtomicIntegerFieldUpdater, AtomicLongFieldUpdater和AtomicReferenceFieldUpdater这3个修改类的成员的原子类型的原理和用法 ...