算法学习1 求两个数的和

来源:互联网 发布:手机签字软件 编辑:程序博客网 时间:2024/05/19 22:05

本文翻译自:https://leetcode.com

问题:

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

例:
给定nums = [2,7,11,15],target = 9,
因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9,
返回[ 0,1 ]。

答案:

方案一 :穷举法

穷举法很简单,循环nums里面的每一个元素x,查找是否有另一个元素的值等于target-x

public int[] twoSum(int[] nums, int target) {    for (int i = 0; i < nums.length; i++) {        for (int j = i + 1; j < nums.length; j++) {            if (nums[j] == target - nums[i]) {                return new int[] { i, j };            }        }    }    throw new IllegalArgumentException("No two sum solution");}

复杂度分析:

时间复杂度:O(n2)
(n-1) + (n-2) + (n-3) + ... + 2 + 1 = n*(n-1)/2 == O(n2)

空间复杂度:O(1)
仅使用了一个额外变量,并且与n无关:new int[] { i, j }

方案二:略

(同方案三类似,但是需要两次循环)

方案三:一次遍历+HashMap

循环数组nums中的每一个元素x,将x存入map的同时判断map中是否存在target-x对应的值。如果存在,直接返回x和target-x对应的下标即可。

public int[] twoSum(int[] nums, int target) {    Map<Integer, Integer> map = new HashMap<>();    for (int i = 0; i < nums.length; i++) {        int complement = target - nums[i];        if (map.containsKey(complement)) {            return new int[] { map.get(complement), i };        }        map.put(nums[i], i);    }    throw new IllegalArgumentException("No two sum solution");}

复杂度分析:

时间复杂度:O(n)
遍历n个元素的数组(仅一次遍历)中的每一个元素,每次在map中查找耗时O(1)。

空间复杂度:O(n)
额外的变量就是map:里面存放了n个元素。

小结:

方案三的时间复杂度明显好于方案一。稍显不足的是方案三的空间复杂度为O(n)比方案一的O(1)更耗费空间。

参考

https://leetcode.com/problems/two-sum/description/

原创粉丝点击