写在前面:
之前因为项目、课程各种原因,偷懒了很久,现在基本大作业结束了,过一段时间要去实习了,所以一定一定要坚持继续刷题,本来是习惯cpp的,后来因为很多课程用到java,找实习也发现java工程师的需求大过cpp开发工程师,所以转用java了,几乎是从头开始,一定要坚持,一定要加油!
题目:
思路:
方法1:简单的两层循环,找到nums[i] + nums[j] = target 的 i 和 j 值,返回即可。
方法2:用map,通过寻找对应key值的value,及对应值的坐标(索引index)
这里有一个介绍基础的hashmap操作的博客:
https://blog.youkuaiyun.com/jinqianwang/article/details/80030939
【备注:这里要注意Integer和int是不同的】
Integer和string其实是类似的,都是继承了object 的类,存储在栈中,通过赋初值就可以发现他们的区别
int a = 5;
Integer b = new Integer(10);
OK,接下来是代码:
public class Two_sum_1 {
public static int[] twoSum(int[] nums,int target) {
// 时间复杂度为O(n)
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};
// 普通实现方法,时间复杂度是O(n2)
// int[] res = new int[2];
// for(int i = 0;i < nums.length;i++){
// for(int j = i+1; j < nums.length; j++){
// if(nums[i] + nums[j] == target)
// return new int[]{i,j};
// }
// }
// return res;
}
public static void main(String[] args){
int[] nums = new int[]{1,3,4,8,5};
int target = 8;
int[] res;
res = twoSum(nums,target);
for(int i = 0; i < res.length;i++)
System.out.println(res[i]);
}
}