LeetCode 1. Two Sum(数组中和为某数的两个整数的角标数组)

题目地址:https://leetcode.com/problems/two-sum/description/


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


核心思想:

 利用hashmap在遍历一次的情况下,先存储数组中数字和角标的对应关系和判断是否含有target-this。


   /**
     * 整形数组,找出和为某数的两个数字
     * @param nums  整型数组
     * @param target 目标数字
     * @return 满足和为target的两个整数
     */
    public int[] twoSum2(int[] nums, int target) {
        Map<Integer,Integer> tmpMap = new HashMap<>(nums.length);
        //遍历并记录到Map中
        for (int i = 0; i < nums.length; i++) {
           int complement = target - nums[i];
            if (tmpMap.containsKey(complement)&&tmpMap.get(complement)!=i){
                return new int[]{i,tmpMap.get(complement)};
            }
            tmpMap.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    /**
     * 整形数组,找出和为某数的两个数字
     * @param nums  整型数组
     * @param target 目标数字
     * @return 满足和为target的两个整数
     */
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> tmpMap = new HashMap<>(nums.length);
        //遍历并记录到Map中
        for (int i = 0; i < nums.length; i++) {
            tmpMap.put(nums[i],i);
        }
        //遍历一次直接匹配
        for (int i = 0; i < nums.length; i++) {
            if (tmpMap.containsKey(target - nums[i])&&tmpMap.get(target - nums[i])!=i){
                return new int[]{i,tmpMap.get(target - nums[i])};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页