您的位置:首页 > 其它

LeetCode OJ 1. Two Sum

2016-01-19 09:30 351 查看
题目:

https://leetcode.com/problems/two-sum/

题目大意

  已知一个数组的所有数值和一个目标值,找到数组中的两个数的索引使得这两个数的和恰好等于目标值。
用Map接口:

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