描述

LeetCode 原题

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

大意就是给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数,返回这两个数字在数组中位置。

解法一:暴力解法

使用两层 for 循环,找到满足条件的两个元素就将他们的位置返回。这种方法称为暴力解法,也是一开始想到的解法。

public int[] getIndices(int[] numbers,int target){
    if(numbers == null || numbers.length < 2){
        return null;
    }

    int length = numbers.length;
    for (int i=0; i<length; i++){
        for (int j=i+1; j<length; j++){
            if(numbers[i] + numbers[j] == target){
                return new int[]{i,j};
            }
        }
    }
    return null;
}
  • 时间复杂度:O(n^2)。遍历一趟数组时间复杂度 O(n),双层遍历的时间复杂度就是 O(n^2)。

  • 空间复杂度:O(1)。

解法二:HashMap 法

用一个 Map 存储值与索引,for 循环判断差值是否存在 Map 中,存在即返回索引数值。此方法效率较高。

public int[] getIndices(int[] numbers,int target){
    if(numbers == null || numbers.length < 2){
        return null;
    }

    int length = numbers.length;
    Map<Integer,Integer> map = new HashMap();
    for(int i = 0; i < length; i ++){
        int complement = target - numbers[i];
        if(map.containsKey(complement)){
            return new int[] {map.get(complement),i};
        }
        map.put(numbers[i],i);
    }

    return null;
}
  • 时间复杂度:O(n)。遍历一趟数组时间复杂度 O(n),从 Map 中查找时间复杂度 O(1)。

  • 空间复杂度:O(n)。Map 存储键值对增加了额外的空间开销,最大存储 n 个键值对。额外的空间开销取决于 Map 键值对数量。