新旧博客已经迁移、维护在掘金平台,点这里 访问我的掘金博客主页
题意:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
解题:
-
暴力双循环法
时间复杂度:O(n^2),双重循环外循环为n,内循环为n。
/** * 暴力双重循环方式 */ public static int[] twoSum1(int[] nums, int target) { if (null == nums) { return null; } final int LENGTH = nums.length; for (int i = 0; i < LENGTH - 1; i++) { for (int j = i; j < LENGTH; j++) { if (target == nums[i] + nums[j]) { return new int[] {i, j}; } } } return new int[] {}; }
-
构建Hash结构存储数据
时间复杂度:O(n),外循环为n,从 Hash 中读取数据为 O(1)。
/** * 以空间换时间,将访问过的数据存储到 Hash 表中,再次读取即为非线性读取,效率高 */ public static int[] twoSum2(int[] nums, int target) { if (null == nums) { return null; } final int LENGTH = nums.length; // 初始化 hash 容器容量 HashMap<Integer, Integer> numHashMap = new HashMap<>(LENGTH); Integer temp; for (int i = 0; i < LENGTH; i++) { int devideValue = target - nums[i]; temp = numHashMap.get(devideValue); if (null != temp) { return new int[] {temp, i}; } numHashMap.put(nums[i], i); } return new int[]{}; }
-
如果给出题目中数组值是 递增 的,则还可以使用双指针来优化
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
public static int[] twoSum3(int[] nums, int target) { if (null == nums) { return null; } final int LENGTH = nums.length; int head = 0, tail = LENGTH - 1; while (head < tail) { int temp = nums[head] + nums[tail]; if (temp > target) { tail--; } else if (temp < target) { head++; } else { return new int[] {head, tail}; } } return new int[] {}; }