问题表示提供一个整数数组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 进行数据挖掘 ——第一章:简介

    1.简介数据挖掘.机器学习这些字眼,在一些人看来,是门槛很高的东西.诚然,如果做算法实现甚至算法优化,确实需要很多背景知识.但事实是,绝大多数数据挖掘工程师,不需要去做算法层面的东西.他们的精力,集中 ...

  2. Windows10重启之后总是将默认浏览器设置为IE

    换了一台电脑之后,发现系统重启之后总是会把我的默认浏览器设置为IE,而自从用上了Chrome,我对他爱不释手. 上网找了不少文章,都建议使用系统自带的设置进行默认浏览器的设置,试了三四次,完全不起任何 ...

  3. 解决pip安装太慢的问题

    经常在使用Python的时候需要安装各种模块,而pip是很强大的模块安装工具,但是由于国外官方pypi经常被墙,导致不可用,所以我们最好是将自己使用的pip源更换一下,这样就能解决被墙导致的装不上库的 ...

  4. mysql 视图,触发器,存储

    一.视图 概念:其实就是一个临时表. 视图是一个虚拟表(非真实存在的),其本质是[根据SQL语句获取动态的数据库,并为其命名],用户使用时只需使用[名称]即可获取结果集.就可以当做表来使用. # 1. ...

  5. 【框架】Django入门学习笔记

    教程 Demo 教材2 教材3 [转] Django处理请求的工作机制 记住: 1.用manage.py runserver 启动Django服务器时就载入了在同一目录下的settings.py.该文 ...

  6. SGU 505 Prefixes and suffixes

    题解   现将字符串排序: 那么某前缀在字符串中出现肯定是连续的:写几个案例就知道了:这是记录每个字符在以前缀排名的rank : 然后将字符串反序: 再排序:依照前缀,可以知道相同名字的后缀也会出现在 ...

  7. (转)移动端开发总结(一)视口viewport总结

    转载链接:移动端开发中,关于适配问题的一点总结(一) 视口 布局视口layout viewport 视觉视口visual viewport 理想视口 缩放 一个重大区别 最小缩放 和最大缩放 分辨率 ...

  8. 关于fft后图像的纵轴问题

    fft后如果纵轴是abs后的值,且为双边图像,那么纵轴表示的就是此频率下信号的幅值*N/2的值,也就是说,如果有一正弦信号,幅度为1,假如fft了50个点,那么此信号频率的幅度就是1*50/2=25. ...

  9. 【策略】一致性Hash算法(Hash环)的java代码实现

    [一]一致性hash算法,基本实现分布平衡. package org.ehking.quartz.curator; import java.util.SortedMap; import java.ut ...

  10. 简述MVC模式

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...