您的位置:首页 > 其它

LeetCode-1. Two Sum

2016-03-28 21:07 302 查看
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.

Example:

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){
int N = nums.length;
for(int i = 0; i<N; i++){
for(int j = i+1; j<N; j++){
if(nums[i] + nums[j] == target){
int[] re = {i,j};
return re;
}
}
}
return null;
}
}


结果发现只击败了11%的用户。。。于是。。

import java.util.Map;
import java.util.HashMap;

public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i = 0 ; i < nums.length ; i++){
map.put(nums[i], i);
}
for(int i = 0; i<nums.length;i++){
int gap = target-nums[i];
if(map.containsKey(gap) && map.get(gap)!=i){
res[0] = i;
res[1] = map.get(gap);
break;
}
}
return res;
}
}


然后就击败百分之三十多了。。





leetcode第一题~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: