leetcode
Java
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
給一個整數數組,找到兩個數使得他們的和等於一個給定的數 target。 你需要實現的函數twoSum需要返回這兩個數的下標, 並且第一個下標小於第二個下標。注意這裡下標的範圍是 0 到 n-1
target
,時間複雜度偏高target
和當前數字相減並存在HashMap裏並在接下來的迴圈當中檢查當前數字在HashMap中是否有相同數字map.get(nums[i])!=null
代表HashMap中有我要的數字方法二相較於方法一暴力解法整整快出了50倍
Runtime: 48 ms, faster than 28.98% of Java online submissions for Two Sum. Memory Usage: 39.4 MB, less than 37.92% of Java online submissions for Two Sum.
Runtime: 1 ms, faster than 99.59% of Java online submissions for Two Sum. Memory Usage: 39.2 MB, less than 50.00% of Java online submissions for Two Sum.