算法每日禅

来源:互联网 发布:itc网络广播功放说明书 编辑:程序博客网 时间:2024/06/05 20:10

问题描述

给定一个int型数组,返回其中数组中两元素相加之和等于给定的目标值的下标,如:

input:[3,2,3] target:6return:[0,2]

方案1:

java实现

public static int[] twoSum(int[] nums, int target) {        if (nums == null || nums.length < 2) {            throw new IllegalArgumentException();        }        for (int i = 0; i < nums.length - 1; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    return new int[]{i, j};                }            }        }        throw new IllegalStateException("not found");}

算法分析

  • 时间复杂度:
    由于对于每一个元素,都是从剩余元素中遍历查询,所以时间复杂度为:
T = O(n^2)
  • 空间复杂度:
S = O(1)

方案2

有没有其它解决方案呐,使其效率更优?

由于我们需要的结果是满足条件的元素的下标,那是否可以考虑用元素做键用下标做值来建立一个hashmap呐?

java实现

public static int[] twoSum(int[] nums, int target) {    if (nums == null || nums.length < 2) {        throw new IllegalArgumentException();    }    /*for (int i = 0; i < nums.length - 1; i++) {        for (int j = i + 1; j < nums.length; j++) {            if (nums[i] + nums[j] == target) {                return new int[]{i, j};            }        }    }*/    HashMap<Integer, Integer> map = new HashMap<>();    for (int i = 0; i < nums.length; i++) {        map.put(nums[i], i);    }    for (int i = 0; i < nums.length; i++) {        int element = target - nums[i];        if (map.containsKey(element) && map.get(element) != i) {            return new int[]{i, map.get(element)};        }    }    throw new IllegalStateException("not found");}

算法分析


  • 时间复杂度:

由于借助于hashmap的辅助,只是对数组遍历了2次,所以其时间复杂度为2*O(n)为:
T = O(n)


  • 空间复杂度:

多余了辅助空间为N个数组元素。
S = O(n)
原创粉丝点击