我的第一个在LeetCode上答得题目,以下分别是我得解法与参考优秀博客的解法,总结记录。
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].
我的解法(java)是使用两个简单的for循环,穷举出所有的数进行加法运算:
public class AlgorithmTest1 {
public static void main(String[] args) {
int[] nums = {2,-2,11,15,-33};
int target = -31;
int[] result = twoSum(nums, -31);
System.out.println(result[0] + " " + result[1]);
}
public static int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
int k=0,f=0;
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(target == nums[i]+nums[j]){
k=i;
f=j;
result[0] = k;
result[1] = j;
break;
}
}
}
return result;
}
}
这个在LeetCode上是通过的,其时间复杂度为O(n^2),空间复杂度为O(1),之后我在LeetCode上看到相对更优解的做法,是利用hashmap将空间复杂度变大时间复杂度降低,各为O(n)。
之后我利用该做法重新写了该方法:
public static void main(String[] args) {
int[] nums = {3,2,4,5};
int[] result = twoSum1(nums, 8);
System.out.println(result[0] + " " + result[1]);
}
public static int[] twoSum1(int[] nums, int target) {
int[] results = new int[2];
//创建hashmap用来存放<元素,元素的下表>
Map<Integer, Integer> map = new HashMap<>();
//将数组-数组下标以key-value的方式存入map中
for(int i=0; i<nums.length; i++){
map.put(nums[i], i);
}
//边扫描边查询
for(int i=0; i<nums.length; i++){
int cursor = nums[i];
int result = target-cursor;
//查询当前目标与数组的差值是否存在map中,如果存在说明当前数组元素与map值相加和为当前目标
//判定是否存在该差值时,要同时判断该差值的下标是不是当前遍历的元素下标,以避免重复
if(map.containsKey(result) && map.get(result) != i ){
System.out.println(map.get(result));
results[0] = i;
results[1] = map.get(result);
break;
}
}
return results;
}
}
其中,在LeetCode中关于该题目列出了几个优秀的做法,参考链接
:https://leetcode.com/problems/two-sum/solution/