Skip to content

Commit

Permalink
Merge pull request #3 from bingyuhuang/master
Browse files Browse the repository at this point in the history
new algorithm: twosum java && fix bug :add package
  • Loading branch information
sherlockblaze authored Dec 17, 2018
2 parents 14793b0 + 48ab5ff commit 3b878e1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion knowledge/algorithms/combat/code/java/AddTwoNumbers.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import java.util.LinkedList;
import java.util.List;
public class AddTwoNumbers {
public static void addTwoNumber(List<Integer> num1, List<Integer> num2) {
public static List<Integer> addTwoNumber(List<Integer> num1, List<Integer> num2) {

List<Integer> result = new LinkedList<Integer>();
int i = num1.size();
Expand All @@ -19,5 +21,6 @@ public static void addTwoNumber(List<Integer> num1, List<Integer> num2) {
break;
}
}
return result;
}
}
26 changes: 26 additions & 0 deletions knowledge/algorithms/combat/code/java/TwoSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.util.HashMap;
import java.util.Map;

/**
* find two numbers in the arrays
* where a number adds the other equals the target
*/
public class TwoSum {

public static int[] twoSum (int[] arrays, int target) {
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>(arrays.length);
int[] result = new int[2];
for (int i = 0; i < arrays.length; i++) {
if (indexMap.get(arrays[i]) != null){
continue;
}
indexMap.put(arrays[i], i);
if (indexMap.get(target - arrays[i]) != null) {
result[0] = indexMap.get(arrays[i]);
result[1] = indexMap.get(target - arrays[i]);
break;
}
}
return result;
}
}

0 comments on commit 3b878e1

Please sign in to comment.