-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
72 lines (67 loc) · 1.81 KB
/
TwoSum.java
File metadata and controls
72 lines (67 loc) · 1.81 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.leetcode;
import java.util.Arrays;
import java.util.HashMap;
/**
* Author: yhl
* DateTime: 2019/11/4 11:29
* Description: write some description
*/
public class TwoSum {
public static void main(String[] args) {
int[] arr = {3,2,4};
final TwoSum twoSum = new TwoSum();
final int[] ints = twoSum.twoSum3(arr, 6);
System.out.println(Arrays.toString(ints));
}
/**
* brute force
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i < nums.length; i++){
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
/**
* space exchange time
* @param nums
* @param target
* @return
*/
public int[] twoSum2(int[] nums, int target) {
final HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int value = target - nums[i];
if (map.containsKey(value) && map.get(value) != i) {
return new int[]{i,map.get(value)};
}
}
return new int[0];
}
/**
* @param nums
* @param target
* @return
*/
public int[] twoSum3(int[] nums, int target) {
final HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int value = target - nums[i];
if(map.containsKey(value)){
return new int[]{map.get(value), i};
}
map.put(nums[i],i);
}
return new int[0];
}
}