问题表示提供一个整数数组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. boost库做什么用呢?

    1.C++标准库不是已经很全面了吗?Boost又不是界面库,它主要解决些什么问题呢?哪类问题?2.Boost的开发人员都是C++标准委员会的吧,为什么没把它列做标准库,有什么不完善的问题吗? 3.Bo ...

  2. DataBase project physical design

    DataBase physical design //Table: /*student*/ create table student( id int not null primary key, /*学 ...

  3. 牛客国庆集训派对Day1:J:Princess Principal(栈模拟求括号匹配)

    题目描述 阿尔比恩王国(the Albion Kingdom)潜伏着一群代号“白鸽队(Team White Pigeon)”的间谍.在没有任务的时候,她们会进行各种各样的训练,比如快速判断一个文档有没 ...

  4. sql_自连接,181,182,196,197

    181. Employees Earning More Than Their Managers https://leetcode.com/problems/employees-earning-more ...

  5. HDFS的工作原理扫扫盲

    问题导读: 1.什么是分布式文件系统? 2.怎样分离元数据和数据? 3.HDFS的原理是什么? Hadoop分布式文件系统(HDFS)是一种被设计成适合运行在通用硬件上的分布式文件系统.HDFS是一个 ...

  6. 剑指offer-第六章面试中的各项能力(和为S的两个数字VS和为S的连续正序列)

    题目1:输入一个排序数组和一个值S,输出数组中两个数的和为S的任意一对数. 思路:分别用两个指针指向数组的头start和尾end.如果两个数字之和等于S输出.如果打于,则end--,再次相加.因此循环 ...

  7. Git 的 cherry-pick 功能

    简而言之,cherry-pick就是从不同的分支中捡出一个单独的commit,并把它和你当前的分支合并.如果你以并行方式在处理两个或以上分支,你可能会发现一个在全部分支中都有的bug.如果你在一个分支 ...

  8. yii 操作cookie

    原文地址:http://blog.sina.com.cn/s/blog_664c9f650100yqkn.html 设置cookie: $cookie = new CHttpCookie('mycoo ...

  9. super,this

    要说super就先要说this."this",作为一个特殊的关键字,它的规则如下: 1.可以表示构造函数传递.this(a,b)表示调用另外一个构造函数.这里面的this就是一个特 ...

  10. 关于sea.js的笔记

    首先,引入sea.js:(注意要直接写在Script标签里,不要写在jquery的页面加载事件里) seajs.config({ base: "./" //seajs的基础路径(组 ...