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

Commitba26433

Browse files
Merge pull request#1 from shivprakashsinghjii/shivprakashsinghjii-patch-1
Create TwoSum.java
2 parents0d17728 +5c79c19 commitba26433

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎TwoSum.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
importjava.util.HashMap;
2+
3+
publicclassTwoSum {
4+
publicint[]twoSum(int[]nums,inttarget) {
5+
HashMap<Integer,Integer>numToIndex =newHashMap<>();
6+
7+
for (inti =0;i <nums.length;i++) {
8+
intcomplement =target -nums[i];
9+
if (numToIndex.containsKey(complement)) {
10+
returnnewint[] {numToIndex.get(complement),i };
11+
}
12+
numToIndex.put(nums[i],i);
13+
}
14+
15+
thrownewIllegalArgumentException("No solution found.");
16+
}
17+
18+
publicstaticvoidmain(String[]args) {
19+
TwoSumsolution =newTwoSum();
20+
int[]nums = {2,7,11,15};
21+
inttarget =9;
22+
int[]result =solution.twoSum(nums,target);
23+
System.out.println("Indices of the two numbers that add up to the target:");
24+
System.out.println(result[0] +" " +result[1]);
25+
}
26+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp