(1)Two Sum

来源:互联网 发布:淘宝手机一屏尺寸多少 编辑:程序博客网 时间:2024/05/20 14:17

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].
(解法一)
/** * 功能说明:LeetCode 1 - Two Sum * 开发人员: * 开发时间:2016.4.2 */public class Solution{    /**     * 给出指定数组,其中两数字相加之和等于目标数字,求出这两个数字的序号     * @param nums 输入数组     * @param target 目标数字     * @return     */    public int[] twoSum(int[] nums, int target) {                for(int i = 0 ;i <nums.length; i++){            for(int j = i + 1; j<nums.length; j++){            if(nums[i] + nums[j] == target){                return new int[] { i, j};            }            }        }        return new int[] { 0, 0 };    }}
解法二:
public class Solution{        /**     *利用hashmap减少时间复杂度为O(n)     */          public int[] twoSum(int[] num, int target){          Map <Integer,Integer> map = new HashMap <Integer,Integer>();//泛型         for ( int i = 0; i<num.length; i++ ){             map.put(num[i],i);         }
//特别要注意的是不能用一个FOR循环。因为首先要把map装满。         for ( int i = 0; i<num.length; i++ ){            int complement = target-num[i];             if(map.containsKey(complement)&&map.get(complement)!=i){                                return new int[] { i, map.get(complement)};                     }         }         return new int[] { 0,0 };     }}
总结一map中的一些方法。(Object)map.put(Object key,Object value).因为返回对象是Object,采用泛型就不用每次都强制转换。
map.get(key):根据key值拿到相应的value.因为最后我们要返回的是i,所以让num[i]作为key。
map.containsKey(key);
map.containsValue(value);
0 0
原创粉丝点击