LeetCode 刷题记录: 1. Two Sum [Java]

原题

https://leetcode.com/problems/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.

思路

使用hashmap查表,拿到数字首先查找余值是否在表内,若在的话直接返回表内的对应值。接着将数字以及index存入表内。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> h = new HashMap<>();
for(int i=0;i<nums.length;i++){
int residue=target-nums[i];
if(h.containsKey(residue)){
return new int[]{h.get(residue),i};
}
h.put(nums[i],i);
}
throw new IllegalArgumentException("No solution");
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×