LeetCode:一個數組中兩個數的和
阿新 • • 發佈:2018-12-14
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].
題目的要求是:從陣列中找出兩個數,使其和為特定值target。例如nums = [2, 7, 11, 15], target = 9,因為2+7=9,返回[0, 1]。
import java.util.HashMap; /** * @author zhangyu * @version V1.0 * @ClassName: AddTwoNumber * @Description: 在一個數組中找出兩個數剛好等於某個值 * @date 2018/10/12 8:50 **/ public class AddTwoNumber { public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5}; int target = 5; HashMap<Integer, Integer> hashMap = addTwoNumbers(arr, target); for (int key : hashMap.keySet()) { System.out.println(key + ":" + hashMap.get(key)); } } private static HashMap<Integer, Integer> addTwoNumbers(int[] arr, int target) { HashMap<Integer, Integer> hashMap = new HashMap<>(); HashMap<Integer, Integer> newHashMap = new HashMap<>(); for (int i = 0; i < arr.length; i++) { hashMap.put(arr[i], i); } for (int index = 0; index < arr.length; index++) { int num = target - arr[index]; if (hashMap.containsKey(num) && hashMap.get(num) != index && index < hashMap.get(num)) { newHashMap.put(index, hashMap.get(num)); } } return newHashMap; } }
時間複雜度:O(n)
空間複雜度:O(n)