题目链接
https://leetcode.com/problems/two-sum/description/
题目:
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].
第一种解法-暴力破解
思路:
new一个长度为2的数组变量index,通过两层遍历,将满足条件的数组索引放进index,return返回。
时间复杂度O(n^2)不仅耗时,并且不满足题意。“and you may not use the same element twice”,数组相同的元素比较使用不要超过两次。按理提交应该不通过的,但是本人提交之后直接Accepted了
代码实现:
public class TwoSum {
public static void main(String[] arg) {
int[] nums = {2,0,7,15};
int target = 9;
int[] index = towSum(nums,target);
for (int i = 0;i<index.length;i++){
System.out.println(index[i]);
}
}
private static int[] towSum(int[] nums, int target) {
int[] index = new int[2];
for (int i = 0;i < nums.length;i++){
for (int j = i+1;j < nums.length;j++){
if (target == (nums[i] + nums[j])){
index[0] = i;
index[1] = j;
return index;
}
}
}
return index;
}
}
第二种解法-HashMap哈希表
思路:
HashMap是利用哈希表实现键值对key-value集合,元素不能重复,查找效率高。
利用HashMap,key存放数组的数值,value存放对应的数据下标。循环遍历,通过containsKey() 查看 target减去当前数值nums[i],是否在map中,若存在,则通过map的get()方法取出相应的下标值,返回;若不存在,则将当前的键值对(数值,下标)添加到map中。
时间复杂度O(1),空间复杂度O(n)。PS:空间换时间
代码实现:
pubilce static int[] towSum(int[] nums, int target) {
int[] index = new int[2];
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0;i < nums.length;i ++){
if (map.containsKey(target - nums[i])){
index[1] = i;
index[0] = map.get(target - nums[i]);
return index;
} else {
map.put(nums[i],i);
}
}
return index;
}
小知识大道理,一点一滴积累。
(个人微信公众号:TestOnTheRoad,搜索ID或者扫描下方二维码添加关注,关注测试开发工程师的成长之路)