题目地址: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");
    }

原文链接:https://blog.csdn.net/w605283073/article/details/79979671

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《LeetCode 1. Two Sum(数组中和为某数的两个整数的角标数组)
   

还没有人抢沙发呢~