问题表示提供一个整数数组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. WEKA中的数据预处理

    数据预处理包括数据的缺失值处理.标准化.规范化和离散化处理. 数据的缺失值处理:weka.filters.unsupervised.attribute.ReplaceMissingValues. 对于 ...

  2. ng 指令的自定义、使用

    1.创建和使用var app = angular.module('myApp',['ng']);app.directive('指令名称',func); 自定义指令的命名:驼峰式,有两部分构成,前缀一般 ...

  3. VS 2010 转到COFF期间失败。

    可能的原因是framework 版本不匹配,我卸载4.5,装4.0后就解决了

  4. GoogLeNet 神经网络结构

    GoogLeNet是2014年 ILSVRC 冠军模型,top-5 错误率 6.7% ,GoogLeNet做了更大胆的网络上的尝试而不像vgg继承了lenet以及alexnet的一些框架,该模型虽然有 ...

  5. 高级C/C++编译技术之读书笔记(五)之动态库版本控制

    最近有幸阅读了<高级C/C++编译技术>深受启发,该书深入浅出地讲解了构建过程(编译.链接)中的各种细节,从多个角度展示了程序与库文件或代码的集成方法,提出了面向代码复用和系统集成的软件架 ...

  6. LG4360 [CEOI2004]锯木厂选址

    题意 原题来自:CEOI 2004 从山顶上到山底下沿着一条直线种植了 n 棵老树.当地的政府决定把他们砍下来.为了不浪费任何一棵木材,树被砍倒后要运送到锯木厂. 木材只能朝山下运.山脚下有一个锯木厂 ...

  7. php与JAVA的RSA加密互通

    Java 版本RSA 进行加密解密 在网上查询了好几天,最终找到解决方案,网络上都是通过Cipher.getInstance("RSA"); 而改成Cipher.getInstan ...

  8. php无wsdl webservice服务用法

    服务端: <?php class test { function add($a,$b) { return $a+$b; } } function getUserInfo($name) { ret ...

  9. Studio 3T 如何使用 Query Builder 查询数据

    Studio 3T 是一款对 MongoDB 进行数据操作的可视化工具. 在 Studio 3T 中,我们可以借助 Query Builder 的 Drag & Drop 来构建查询条件. 具 ...

  10. 微信小程序生成太阳码

    微信小程序生成太阳码 https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=access_token 必须通过POST提交 而且参数 ...