Leetcode-1.Two Sum

来源:互联网 发布:苹果怎么打开php文件 编辑:程序博客网 时间:2024/06/02 03:58

题目: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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
翻译:给定一个整形数组; 给定一个整数(这个整数是数组中俩个数的和),返回2个数的索引;假设每一个输入的整数有一个确定的解法。
解法:用一个map将数组和下标存储起来,遍历数组中每个元素,判断给定整数与当前元素的差 是否是map中的key。如果是,返回当前元素i和key对应的键值。

public static int[] twoSum(int[] nums, int target) {        int[] res = new int[2];        Map<Integer,Integer> map = new HashMap<Integer,Integer>();        for(int i = 0; i < nums.length; i++){            map.put(nums[i], i);        }        for(int i = 0; i < nums.length; i++){            int remain = target - nums[i];            if(map.get(remain) != null && map.get(remain) != i){                res[0] = i+1;                res[1] = map.get(remain) + 1;                break;            }        }        for(int i = 0; i <= res.length -1; i++){            System.out.print(res[i] + ";\n");        }        return res;    }
0 0