Java实现LeetCode1.两数之和

这篇文章主要介绍了Java实现LeetCode(两数之和),本文使用java采用多种发放实现了LeetCode的两数之和题目,需要的朋友可以参考下

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回[0, 1]

思路一:最直接的思维,两次遍历查询,时间复杂度O(N*N)。

代码

public static int[] twoSum1(int[] nums, int target) { int[] label = new int[2]; for(int i=0;i

思路二:先排序,然后两个指针i,j,i从前开始,j从后开始查找,当nums[i]+nums[j]>target时,j--;当nums[i]+nums[j]

代码

public static int[] twoSum2(int[] nums, int target) { int[] label = new int[2]; int[] tmpArr = new int[nums.length]; for(int i=0;itarget){ j--; }else { i++; } } for(int k=0;k

思路三:利用空间换时间方式,用hashmap存储数组结构,key为值,value为下标。时间复杂度O(N)。

代码

public static int[] twoSum3(int[] nums, int target) { int[] label = new int[2]; HashMap hashMap = new HashMap(); for(int i=0;i

github地址:https://github.com/xckNull/Algorithms-introduction

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...