Skip to content

Commit 65a3f5b

Browse files
authored
Create TwoSum.java
1 parent a4770ca commit 65a3f5b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

TwoSum.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
2+
/*
3+
* Given an array of integers, return indices of the two numbers such that they add up to a
4+
* specific target.
5+
6+
You may assume that each input would have exactly one solution.
7+
8+
Given nums = [2, 7, 11, 15], target = 9,
9+
10+
Because nums[0] + nums[1] = 2 + 7 = 9,
11+
return [0, 1].
12+
*/
13+
14+
15+
16+
17+
public class Solution {
18+
public int[] twoSum(int[] nums, int target) {
19+
int[] result = new int[2];
20+
int sum = 0;
21+
for(int i = 0 ;i < nums.length ; i++){
22+
int temp = nums[i];
23+
for(int j= 0 ;j< nums.length; j++){
24+
if( j != i){
25+
sum = temp + nums[j];
26+
if(sum == target)
27+
{
28+
result[0] = i;
29+
result[1] = j;
30+
if(i > j){
31+
int swap = result[1]; // ignoring the case when result{2,1} comes instaed of {1,2}
32+
result[1] = result[0];
33+
result[0] = swap;
34+
}
35+
break;
36+
}
37+
}
38+
}
39+
40+
41+
}
42+
return result;
43+
}
44+
}
45+

0 commit comments

Comments
 (0)