您的位置:首页 > 其它

Leetcode(1) Two Sum

2016-02-03 01:38 281 查看
https://leetcode.com/problems/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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

今天开始从零单排leetcode, 纪念一些

这题比较简单,但也有几个细节需要注意。这题要求返回数的下标,注意是从1开始。

解法一:双指针暴力解法,时间复杂度O(n2),空间O(1)

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for(int i = 0; i < nums.length-1; i++){
for(int j = i+1; j < nums.length; j++){
if(nums[i]+nums[j] == target){
res[0] = i+1;
res[1] = j+1;
break;
}
}
}
return res;
}
}


解法2:Hashtable, 时间复杂度O(n), 空间复杂度O(1)

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
res[0] = map.get(nums[i])+1;
res[1] = i+1;
break;
}else{
map.put(target-nums[i], i);
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: