算法天天练2:根据和值找到数组元素下标

题目来源: https://leetcode.com/problems/two-sum/
问题描述: 从数组中取出任意两个元素计算和值,根据和值反推元素下标。
举例说明:

define nums = [2, 7, 11, 15], target = 9
Because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
示例数组 示例和值 返回结果 解释
[2, 7, 11, 15] 9 [0,1] 2 + 7 = 9
[2, 3, 10, 15] 12 [0,3] 2 + 10 = 12

解决方案

  1. 双重遍历逐一匹配,时间复杂度Ο(n^2)
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");
}

2.采用map预装其中一个数,虽然时间复杂度是Ο(n),map的集合操作也是耗时的

public int[] twoSum(int[] nums, int target) {
    Map 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 complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

你可能感兴趣的:(算法天天练2:根据和值找到数组元素下标)