您的位置:首页 > 编程语言 > Java开发

LeetCode_1_TwoSum(Java Code)

2016-02-18 22:19 459 查看
Java版

/**
* LeetCode_TwoSum
* @author ChrisWang
* @Date 2016年2月18日 下午9:49:20
* @Description: 给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。
* @Example:输入: numbers={2, 7, 11, 15}, target=9
*          输出: index1=1, index2=2
* @Thinking: 1,使用两个嵌套循环来遍历数组,复杂度:O(n*n)
*            2,使用Map存储对应数的下标,复杂度O(n)
*/
public class Solution {
public static void main(String[] args) {
int[] arr = {3, 2, 9, 10, 5, 7, 8, 1};
int target = 12;
System.out.println(getTwoIndex(arr, target));
}

public static List<Map<String, Integer>> getTwoIndex(int[] arr, int target) {
// 定义一个Map集合用来存放数组中的值以及相应的下标
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// 遍历数组,将数组中的值以及其对应的下标存放到map中
for(int i=0; i<arr.length; i++) {
map.put(arr[i], i);
}
// 用来存放下标
Map<String, Integer> temp = null;
// 存放上面的数组
List<Map<String, Integer>> list = new ArrayList<>();
// 遍历数组查找
for(int i=0; i<arr.length; i++) {
// map中存在要查找的那个值,并且那个值对应的下标不能是当前元素的下标,即不能是当前元素
if(map.containsKey(target-arr[i]) && map.get(target-arr[i])>i) {
temp = new HashMap<>();
temp.put("index_1", i);
temp.put("index_2", map.get(target-arr[i]));
list.add(temp);
}
}
return list;
}
}


输出结果:
[{index_1=0, index_2=2}, {index_1=1, index_2=3}, {index_1=4, index_2=5}]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: