LeetCode|Two Sum-java
2016-09-25 10:02
423 查看
题目
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
需要注意的:数组并不是排序的数组
public class Solution { /** * 思路一: * 将数组拷贝出一份,对数组进行排序,然后使用head和end指针移动查 * 找答案,最后在原数组中查找相应的相应的位置。 * 空间复杂度:o(n) * 时间复杂度:o(nlogn+n+n) = o(nlogn) * * */ public int[] twoSum(int[] nums, int target) { int[] temp = Arrays.copyOfRange(nums, 0, nums.length); Arrays.sort(temp); int head = 0; int end = temp.length - 1; int sum = temp[head] + temp[end]; while (sum != target && head < end) { sum = temp[head] + temp[end]; if (sum < target) { head++; } else if (sum > target) { end--; } } if (head != end) { int[] result = {-1, -1}; for (int i = 0; i < nums.length; i++) { if (nums[i] == temp[head] && result[0] == -1) { result[0] = i; } else if (nums[i] == temp[end] && result[1] == -1) { result[1] = i; } else if (result[0] != -1 && result[1] != -1) { break; } } Arrays.sort(result); return result; } return null; } } public class Solution { /** * 思路二: * 将数组的值和相应的位置信息存储到hashMap中,Key存储数组的值,Value存贮该值得位置, * 然后遍历整个数组,因为数组中有且只有一对数字的合等于目标数字,所以将每次遍历的数字与目标数字相减, * 查看hasMap中是否有相应的结果 * 空间复杂度:o(n) * 时间复杂度:o(n); * * */ public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) return null; HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { hashMap.put(nums[i], i); } int[] result = null; for (int i = 0; i < nums.length; i++) { int num = nums[i]; int res = target - num; if (hashMap.containsKey(res) && hashMap.get(res) != i) { result = new int[2]; result[0] = i; result[1] = hashMap.get(res); break; } } return result; } }
相关文章推荐
- Java 线程同步与死锁 学习笔记
- 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)【转】
- 2017 小米笔试题 编程题 求树的高度 Java代码实现
- Java设计模式--抽象工厂
- 学习Socket类,实现简单聊天室
- springmvc+mybatis+sql server实现简单登录功能【转】
- 在Eclipse中显示.project, .classpath, .gitignore文件和.setting文件夹
- [Scala--基础]--java运行jar类、scala运行jar类
- java基础学习总结--操作符
- 浅析JAVA中toString方法的作用
- Java设计模式--工厂模式(简单工厂+工厂方法)
- ubuntu下安装和配置最新版JDK8傻瓜教程
- 使用StarUML画类图
- Java中的synchronized与volatile关键字
- java项目---迷你DVD
- leetCode练习(39)
- Java设计模式--单例模式
- 在java中instanceof的用法?
- 冒泡排序Java实现
- Java并发编程学习笔记(一)