problem

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:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

approach 1

算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* @lc app=leetcode id=1 lang=java
*
* [1] Two Sum
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if (nums == null || nums.length <= 1) {
return res;
}
Map<Integer, Integer> m = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
Integer pst = m.get(nums[i]);
if (pst == null) {
m.put(target - nums[i], i);
} else {
res[0] = pst;
res[1] = i;
break;
}

}
return res;

}
}

复杂度

  • time:O(n)
  • space:O(n)

approach 2

算法

双循环

复杂度

  • time:O(n^2)
  • space:O(1)

  map

Comments

Your browser is out-of-date!

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

×