今天在Leetcode开刷,选的是第一个题目。
先上题目:
Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
下面是我的解,首先是最耗时间的两层循环解法:
public class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(nums[i]+nums[j]==target){
int[] ret = new int[]{i,j};
Arrays.sort(ret);
return ret;
}
}
}
return null;
}
}
上面这个解法是最常见的,但是由于是两层循环需要耗费n*n-1,下图是AC以后的时间耗费对比:
接着我进行了改进,把两层循环变为了两次循环,借助HashMap实现:
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++){
map.put(nums[i],i);
}
for(int i=0; i<nums.length; i++){
if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i){
int[] ret = new int[]{i,map.get(target-nums[i])};
Arrays.sort(ret);
return ret;
}
}
return null;
}
}
下图是AC以后的时间耗费对比:
接着再次进行了改进,把两次循环变为了一次循环,也是借助HashMap实现,效率有所上升:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ret={};
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++){
if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i){
ret= new int[]{i,map.get(target-nums[i])};
break;
}
map.put(nums[i],i);
}
Arrays.sort(ret);
return ret;
}
}
下图是AC以后的时间耗费对比:
这是我第一次在leetcode上做的第一道题,这是一个开始。