Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題內容是:給定一個數組,給定一個數字。返回數組中可以相加得到指定數字的兩個索引。
比如:給定nums = [2, 7, 11, 15], target = 9
那么要返回?[0, 1],因為2 + 7 = 9
?
這道題的優解是,一次遍歷+HashMap:
先去Map中找需要的數字,沒有就將當前的數字保存在Map中,如果找到需要的數字,則一起返回
代碼:
public int[] testTwoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {return new int[] { map.get(complement), i };}map.put(nums[i], i);}throw new IllegalArgumentException("No two sum solution");}@Testpublic void test4(){int[] nums = {2, 7, 11, 15};int target = 9;int[] j = testTwoSum(nums, target);System.out.println(Arrays.toString(j));}?
總結
以上是生活随笔為你收集整理的Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引的全部內容,希望文章能夠幫你解決所遇到的問題。