Skip to content

Commit

Permalink
create: solution of two sum
Browse files Browse the repository at this point in the history
  • Loading branch information
DivenYoung committed Apr 19, 2020
1 parent 5d33c0a commit 4c7f370
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions Week_01/TwoSum.java
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");
}
}

0 comments on commit 4c7f370

Please sign in to comment.