leet code: Two Sum
题目
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].
思路
要求两个数相加等于target,对数组进行排序。排序之后的数组两边各有一个指针,即指向大元素j和小元素i。两个指针所指元素相加。
若result大于target,则说明大元素需要减小,则j–。若result小于target,则说明小元素需要增大,则i++。即可寻找出结果。
需要注意:
题目要求返回原数组两个数的索引,上面对数组进行排序之后的索引改变了, 所以需要一个另外的数组来保存排序之后的数组每一个元素所对应初始数组的索引位置。
代码
Solution类:
package twosum;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] flag = new int[nums.length]; //辅助记录每个数字的原始数组索引
for(int i = 0; i<nums.length; i++)
flag[i] = i;
//冒泡排序
for(int i=0; i<nums.length; i++)
{
for(int j=1; j<nums.length-i; j++)
{
System.out.println(nums[j] + " " + nums[j-1]);
if(nums[j]<nums[j-1])
{
int temp;
temp = nums[j-1];
nums[j-1] = nums[j];
nums[j] = temp;
temp = flag[j-1];
flag[j-1] = flag[j];
flag[j] = temp;
}
}
}
for (int x: nums) {
System.out.print(x + " ");
}
int[] final_result = new int[2];
for(int i=0, j=nums.length-1; i<=j; )
{
int result = nums[i] + nums[j];
if(result == target)
{
final_result[0] = flag[i];
final_result[1] = flag[j];
break;
}
else
{
if(result > target)
{
j--;
}
else
{
i++;
}
}
}
return final_result;
}
}
main函数,只是写了一个测试例子:
import twosum.Solution;
public class Main {
public static void main(String[] args) {
int[] nums = {3,2,4};
int target = 6;
Solution s = new Solution();
int[] result = s.twoSum(nums, target);
System.out.println(result[0] + " " + result[1]);
}
}
运行结果:
Runtime: 42 ms, faster than 10.23% of Java online submissions for Two Sum.
Memory Usage: 36.6 MB, less than 99.66% of Java online submissions for Two Sum.
反思:
从运行结果反馈来看,速度太慢了,但是占用空间比较少。
之后再看一下别人的代码,比较一下差异吧。
更新
看了一下别人的解法,这个题有两种解法:
-
双指针解法
看了别人的才知道原来我这种解法叫双指针解法,自己不会起名字。
这个题其实可以用暴力搜索的方式解决,但是太浪费时间了。改进的方法就是用空间换时间喽,先对原数组排序,快速排序的话时间复杂度是O(nlogn),同时需要记录排序前后数字的位置变化。然后分别在排序后的数组前后设置两个指针,每个比较头尾两个数的和,根据两数之和和target的大小比较,挪动指针,直到找到解。 -
利用hashmap解法
hashmap存储的是数组中每个元素值在数组中的位置索引,即hashmap<Integer,Integer>, 第一个Integer是元素值,第二个Integer是位置索引。遍历一遍数组,将遍历结果存到hashmap中。
遍历数组,用target减当前值寻找另一个数,直接在hashmap中检索,存在key,并在value不等于当前值的索引,则成功找到解。
这种方法的时间复杂度是O(n)。