您的位置:首页 > 其它

#1 Two Sum(Easy)

2017-02-10 17:37 274 查看

题目描述

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].


My Solution

简单暴力的双重循环

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


nums[i] + nums[j] == target 存在缺陷,应改为 nums[i] == target - nums[j] 避免超出int的范围。

Editorial Solution

上述解法为O(n^2)的时间复杂度,O(1)的空间复杂度。可以利用hashMap的思想使得复杂度都变为O(n)。Map的使用可以预处理,也可以一次遍历的过程中处理。

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