美文网首页LeetCode
LeetCode-array-Two Sum

LeetCode-array-Two Sum

作者: 萤火之森ss | 来源:发表于2017-06-29 15:45 被阅读20次

题目:
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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

意思明确,返回数组中两数和为target值得下标

代码如下:

public class TwoSum {
    public static void main(String[] args) {
        TwoSumImpl t = new TwoSumImpl();
        int s[] ={5,2,5, 11};
        int tag = 10;
        int [] result = t.twoSum(s,tag);
        System.out.println(" ======= "+Arrays.toString(result));
    }
}

class TwoSumImpl {
    public  int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) { // 核心
                System.out.println(map);
                result[1] = i ; //i的顺序和数组的下标一致
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            //最开始我是将数组中所有的值先put进去,在这个for循环外面,发现,数组有重复数字
            //行不通,,,智商压制
            map.put(numbers[i], i );
        }
        return result;
    }
}

相关文章

网友评论

    本文标题:LeetCode-array-Two Sum

    本文链接:https://www.haomeiwen.com/subject/hvnmcxtx.html