Two Sum

来源:互联网 发布:php usleep 性能 编辑:程序博客网 时间:2024/06/06 08:48

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

    public int[] twoSum(int[] nums, int target) {        Map<Integer, Integer> map = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            int rest = target - nums[i];            if (map.containsKey(rest)) {                return new int[] {map.get(rest),i};            }            map.put(nums[i], i);        }        throw new IllegalArgumentException("不存在");    }

可以去官网测试,或者

    public static void main(String[] args) {        int[] nums={2,3,4};        int target=6;        TwoSum ts=new TwoSum();        System.out.println(Arrays.toString(ts.twoSum(nums, target)));        System.out.println(nums);    }

额外说一点:最后的输出一个输出数组,另一个则会输出哈希值

0 0
原创粉丝点击