JAVA解决两数之和
题目描述
进阶考虑:
方法一:
双循环
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i<nums.length;i++){
for(int j = 0;j<nums.length;j++){
if(nums[i]+nums[j] == target&&i!=j){
if(i<j){
return new int[]{i,j};
}else{
return new int[]{j,i};
}
}
}
}
return new int[]{-1,-1};
}
}
运行截图
总结:
使用for循环虽然简单粗暴,且容易理解,但是费时费内存
方法二(考虑进阶):
使用Java提供的Map集合存储数组值和数组值对应的下标
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<nums.length;i++){
int temp = target - nums[i];
if(map.containsKey(temp) && map.get(temp) !=i){
return new int[]{map.get(temp),i};
}else{
map.put(nums[i],i);
}
}
return new int[2];
}
}
运行截图