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

2021-08-27 16:13:21 浏览数 (1)

题目地址: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:

代码语言:javascript复制
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0]   nums[1] = 2   7 = 9,
return [0, 1].

核心思想:

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

代码语言:javascript复制
   /**
     * 整形数组,找出和为某数的两个数字
     * @param nums  整型数组
     * @param target 目标数字
     * @return 满足和为target的两个整数
     */
    public int[] twoSum2(int[] nums, int target) {
        Map 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 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");
    }

0 人点赞