Movatterモバイル変換


[0]ホーム

URL:


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

Commit0984ef6

Browse files
committed
hasmap
1 parentc7a2647 commit0984ef6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎sequence/TwoSum.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
packageAlgorithms.sequence;
2+
3+
importjava.util.HashMap;
4+
5+
/*
6+
* Two Sum Total Accepted: 36938 Total Submissions: 200732 My Submissions Question Solution
7+
Given an array of integers, find two numbers such that they add up to a specific target number.
8+
9+
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
10+
11+
You may assume that each input would have exactly one solution.
12+
13+
Input: numbers={2, 7, 11, 15}, target=9
14+
Output: index1=1, index2=2
15+
* */
16+
17+
publicclassTwoSum {
18+
publicint[]twoSum(int[]numbers,inttarget) {
19+
HashMap<Integer,Integer>map =newHashMap<Integer,Integer>();
20+
int[]ret =newint[2];
21+
22+
for (inti =0;i <numbers.length;i++) {
23+
if (map.containsKey(target -numbers[i])) {
24+
25+
// As the index is not ZERO based, we should add one to the result.
26+
ret[0] =map.get(target -numbers[i]) +1;
27+
ret[1] =i +1;
28+
returnret;
29+
}
30+
map.put(numbers[i],i);
31+
}
32+
33+
returnret;
34+
}
35+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp