美文网首页
1. Two Sum --LeetCode java

1. Two Sum --LeetCode java

作者: 姜小姜小 | 来源:发表于2018-12-11 08:21 被阅读0次

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

```

private static int[] getTargetArray(int[] arr, int target) {

if (arr == null || arr.length == 0) return null;

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

int index1 = 0;

int index2 = 0;

for (int i = 0; i < arr.length; i++) {

if (map.containsKey(target - arr[i])) {

index1 = map.get(target - arr[i]);

index2 = i;

int[] targetArr = {index1,index2};

return targetArr;

} else {

map.put(arr[i], i);

}

}

return null;

```

相关文章

网友评论

      本文标题:1. Two Sum --LeetCode java

      本文链接:https://www.haomeiwen.com/subject/yqajhqtx.html