forked from algorithm008-class02/algorithm008-class02
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5d33c0a
commit 4c7f370
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
public class TwoSum { | ||
/** | ||
* The Brute Force Solution | ||
* | ||
*/ | ||
public int[] twoSumBruteForce(int[] nums, int target) { | ||
for (int i = 0; i < nums.length; i++) { | ||
for (int j = i + 1; j < nums.length; j++) { | ||
if (nums[j] == target - nums[i]) { | ||
return new int[]{i, j}; | ||
} | ||
} | ||
} | ||
throw new IllegalArgumentException("No two sum solution"); | ||
} | ||
|
||
/** | ||
* The Solution By Hash Table | ||
* | ||
*/ | ||
public int[] twoSumHashTable(int[] nums, int target) { | ||
Map<Integer, Integer> map = new HashMap<>(); | ||
for (int i = 0; i < nums.length; i++) { | ||
if (map.containsKey(target - nums[i])) { | ||
return new int[]{map.get(target - nums[i]), i}; | ||
} | ||
map.put(nums[i], i); | ||
} | ||
throw new IllegalArgumentException("No two sum solution"); | ||
} | ||
} |