Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 47ad9d1

Browse files
committed
chore: leetcode #1 two sum
1 parent f39b0f9 commit 47ad9d1

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package algorithm_sites.leetcode;
2+
3+
import java.util.*;
4+
5+
public class LC_00001_TowSum {
6+
7+
public int[] twoSum_1(int[] nums, int target) {
8+
if (nums.length == 2) {
9+
return new int[] {0,1};
10+
}
11+
12+
for (int i = 0; i < nums.length-1; ++i) {
13+
for (int j = i+1; j < nums.length; ++j) {
14+
if (nums[i] + nums[j] == target) {
15+
return new int[] {i, j};
16+
}
17+
}
18+
}
19+
20+
return null;
21+
}
22+
23+
public int[] twoSum_2(int[] nums, int target) {
24+
if (nums.length == 2) {
25+
return new int[] {0,1};
26+
}
27+
28+
Map<Integer, Integer> map = new HashMap<>();
29+
for (int i = 0; i < nums.length; ++i) {
30+
map.put(nums[i], i);
31+
}
32+
33+
for (int i = 0; i < nums.length; ++i) {
34+
if (map.containsKey(target-nums[i])) {
35+
if (map.get(target-nums[i]) != i) {
36+
return new int[] {map.get(target-nums[i]), i};
37+
}
38+
}
39+
}
40+
41+
return null;
42+
}
43+
44+
public int[] twoSum_3(int[] nums, int target) {
45+
if (nums.length == 2) {
46+
return new int[] {0,1};
47+
}
48+
49+
Map<Integer, Integer> map = new HashMap<>();
50+
for (int i = 0; i < nums.length; ++i) {
51+
if (map.containsKey(target-nums[i])) {
52+
return new int[] {map.get(target-nums[i]), i};
53+
}
54+
map.put(nums[i], i);
55+
}
56+
57+
return null;
58+
}
59+
60+
public static void main(String args[]) {
61+
LC_00001_TowSum lc = new LC_00001_TowSum();
62+
63+
int[] result = lc.twoSum_3(new int[]{3, 2, 4}, 6);
64+
65+
for (int i = 0; i < result.length; ++i) {
66+
System.out.print(result[i] + " ");
67+
}
68+
}
69+
70+
}
71+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /