这篇文章主要介绍了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