LeetCode0001-俩数之和
题目:
给定一格整数数组 nums 和一个目标值 target ,请你在该数组中找出和为目标值的俩个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用俩遍。
示例:
给定 nums = [2, 7, 11, 15],target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
Java程序实现:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution01 {
public int[] twoSum(int[] sums, int target) {
for (int i = 0; i < sums.length; i++) {
for (int j = i + 1; j < sums.length; j++) {
if (sums[i] + sums[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
class Solution02 {
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 index = target - nums[i];
if (map.containsKey(index) && map.get(index) != i) {
return new int[]{i, map.get(index)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
class solution03 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int index = target - nums[i];
if (map.containsKey(index)) {
return new int[]{map.get(index), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
public class Study0001 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(new Solution02().twoSum(nums, target)));
}
}
结果: