问题描述:
给定一个整数数组
nums和一个整数目标值target,请你在该数组中找出 和为目标值target的那 两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。示例 2:
输入:nums = [3,2,4], target = 6 输出:[1,2]示例 3:
输入:nums = [3,3], target = 6 输出:[0,1]
暴力枚举:
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for( int i = 0 ; i < n; i++){
for(int j = i+1; j<n; j++){
if(nums[i]+nums[j] == target){
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
Hash表:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hashtable.containsKey(target - nums[i])) {
return new int[] { i, hashtable.get(target - nums[i]) };
}
hashtable.putIfAbsent(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
带输入输出整体代码
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
//hot 1:两数之和
//注释掉的为暴力枚举
class SolutiontwoSum{
public int[] twoSum(int []nums, int target){
// int i,j,n;
// for (i = 0;i<nums.length;i++){
// for(j= i+1;j<nums.length;j++){
// if(nums[i]+nums[j]==target){
// return new int[]{i,j};
// }
// }
// }
HashMap<Integer,Integer> hashMap = new HashMap<>();
for (int i = 0;i<nums.length;i++){
if(hashMap.containsKey(target-nums[i])){
return new int[] {hashMap.get(target-nums[i]),i};
}
hashMap.put(nums[i],i);
}
return null;
}
public static void main(String[] args) {
SolutiontwoSum solution = new SolutiontwoSum();
int[]nums = {3,2,4};
int target = 7;
int[] result = solution.twoSum(nums,target);
System.out.println("输入:nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("输出:" + Arrays.toString(result));
}
}
636

被折叠的 条评论
为什么被折叠?



