LeetCode & Q1-Two Sum-Easy

时间:2023-03-09 15:21:17
LeetCode & Q1-Two Sum-Easy

Array Hash Table

Question

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].

我的解答如下:

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] temp = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
temp[0] = i;
temp[1] = j;
}
}
}
return temp;
}
}

时间复杂度:$O(n^{2})$

空间复杂度:$O(1)$

最优解:

public int[] twoSum(int[] nums, int target) {
Map<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 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");
}

时间复杂度为:$O(n)$