您的位置:首页 > 其它

leetcode-two sum

2017-05-09 11:13 197 查看

        lz决定增长自己的算法水平了,因为自己不可能一直做低层次的编写代码工作。lz最近在关注牛客网,他真的是一个很棒的网站,在这里更加看清了自己和外面的差距,同时也找到了解决差距的办法。其中就有leetcode,好了闲话少叙,开始记录我的LeetCode!

1. Two Sum:

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


代码:

/***
* leetcode 1.two sum
* 题意:给定一个整数数组nums和一个整数target,要你求出nums数组哪两个元素相加等于target,并返回两个元素的下标
* 约束条件:1.两个元素的下标不能相同,即不能是同一个元素     2.nums总能有正解
* 解题思路:既然两个元素不能相同,则用map来保存数组元素和下标,键为数组元素,值为数组下标。循环遍历nums,将当前数组元素放入到map中,判断如果map中含有target-nums[i]的键,有则nums[i]就是第二个元素,target-nums[i]就是第一个元素
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode