LeetCode_1_TwoSum(Java Code)
来源:互联网 发布:tp3.2数据库配置 编辑:程序博客网 时间:2024/05/17 05:17
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}]
1 0
- LeetCode_1_TwoSum(Java Code)
- LeetCode之路——LeetCode_1_TwoSum
- gray-code Java code
- Java code
- java code
- code.java
- code.java
- java code
- Java Code To Byte Code
- Java Code To Byte Code
- Code Review for Java code
- Java-XPath(code)
- java code 查询
- Protect your java code
- DES JAVA source code
- dom4j(Java code)
- java exception code
- 正则表达式-Java code
- 数据表写操作卡住,导致所有的注册失败
- kvm虚拟化学习(更新中...)
- unable to load native-hadoop library for your platform using builtin-java classes
- 安卓解决adb被占用的问题
- 二叉树的深度&判断一棵二叉树是否是平衡二叉树&110. Balanced Binary Tree
- LeetCode_1_TwoSum(Java Code)
- 用EL表达式取List<Map<String, Object>>map的值(查阅了很久,总结一下)
- 基于zepto或jquery的手机端弹出框成功,失败,加载特效
- Windows窗口及对话框
- [Lintcode]Majority Number
- 【003】Mac在命令行下下载文件
- 最详细的Log4j使用教程
- UILable用法
- UVaOJ10282