[1] Two Sum

Updated on in LeetCode with 0 views and 0 comments

题目

Two Sum

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].

解法

一:暴力搜索

两个for循环即可

Runtime

45ms

Beats 34.19% of users with Java

二:使用HashMap

思路

for循环数组,从HashMap中查找结果,找到则返回结果,否则将该位放入HashMap

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])){
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return null;
    }
}

Runtime

2 ms
Beats 97.88% of users with Java