Two Sum

来源:互联网 发布:手机拨打电话软件 编辑:程序博客网 时间:2024/06/05 23:52

问题描述:对于一个整数数组,给定一个值target,找出数组中两个元素和为target并返回这两个元素下标组成的数组。


解决:使用HashMap,存储的键为nums[i],值为i.每次从nums数组中拿到一个值a去map中查找是否有target-a这个键。这样的方式时间复杂度为o(n)

/* * 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 */class A1 {            public int[] twoSum(int[] nums, int target) {        int[] rtn = new int[2];        if(nums == null || nums.length<2) {                return null;        }        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length);        for(int i=0; i<nums.length; i++) {                if(map.containsKey(target-nums[i])) {                        rtn[0] = map.get(target-nums[i]);                        rtn[1] = i;                        return rtn;                }                map.put(nums[i], i);        }        return null;    }}