LeetCode|Two Sum-java
来源:互联网 发布:会计软件的基本功能 编辑:程序博客网 时间:2024/06/05 03:24
题目
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; }}
0 0
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- 【Leetcode】two sum JAVA
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- leetcode:Two Sum 【Java】
- LeetCode|Two Sum-java
- leetcode Two Sum(Java)
- LeetCode – Two Sum (Java)
- [LeetCode java] 1.Two Sum
- LeetCode(001) Two Sum (Java)
- LeetCode 1 Two sum Java
- [leetcode-1]Two Sum(java)
- LeetCode – Two Sum (Java)
- LeetCode 1 - Two Sum ( JAVA )
- LeetCode(java)1. Two Sum
- leetcode 1. Two Sum -----java
- 通过fir工具自动打包ipa
- ASP.NET GridView的Bootstrap分页样式
- HDU-5904 LCIS(dp)
- hud 2838 Cow Sorting 树状数组求逆序数
- 【GDOI模拟】妮厨的愤怒
- LeetCode|Two Sum-java
- airflow详细安装过程
- iOS 静态类库 打包 C,C++文件及和OC混编
- 利用Use Case为系统行为建模(1)
- pom.xml中添加各种依赖
- Android事件分发机制完全解析,带你从源码的角度彻底理解(下)
- mjpg-streamer学习笔记7------输出通道
- Hadoop2笔记
- 国产密码算法:锻造信息安全之盾