题目:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。
Java版代码1(时间复杂度O(n)):
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
Integer index=map.get(target-nums[i]);
if(index==null){
map.put(nums[i],i);
}else{
return new int[]{i,index};
}
}
return new int[]{0,0};
}
}
Java版代码2(时间复杂度O(n^2)):
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=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){
return new int[]{i,j};
}
}
}
return result;
}
}

本文深入探讨了经典的“两数之和”算法问题,提供了两种解决方案:一种使用哈希表实现,时间复杂度为O(n),另一种采用双重循环,时间复杂度为O(n^2)。文章详细介绍了如何通过查找数组中两个数的下标,使它们的和等于给定的目标值。
213

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



