[LeetCode]1. Two Sum
来源:互联网 发布:平板电脑推荐 知乎 编辑:程序博客网 时间:2024/06/11 15:49
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].
解法1:暴力
这道题最原始的方法当然是暴力解法,两个for循环就能解决问题,这样的时间复杂度是O(n2),空间复杂度是O(1).
public class Solution { public int[] twoSum(int[] nums, int target) { int[] arrSum = new int[2]; //如果数组长度小于2就不用继续往下了 if(nums==null||nums.length<2){ return arrSum; } for(int i=0;i<nums.length-1;i++){ for(int j=i+1;j<nums.length;j++){ if(nums[i]+nums[j]==target){ arrSum[0]=i; arrSum[1]=j; } }<span style="white-space:pre"></span> }
<span style="white-space:pre"></span>return arrSum;
} }解法2:双指针
我们知道如果我们用两个指针来进行一头一尾扫描的话,那么我们是可以得到所需要的两个index的,所以只需要对数组进行一下排序即可,然后用双指针来进行扫描,把扫到的index放进新数组返回即可。时间复杂度O(nlogn+n)=O(nlogn),空间复杂度O(1).注:我写的时候没有考虑返回之前数组的index,所以不能直接copy此代码submit,你需要自己再loop一遍原来的数组再取得所需要的index
public class Solution { public int[] twoSum(int[] nums, int target) { int[] arrSum = new int[2]; if(nums==null||nums.length<2){ return arrSum; } Arrays.sort(nums); int left=0; int right=nums.length-1; while(left<right){ if(nums[left]+nums[right]==target){ arrSum[0]=left; arrSum[1]=right; break; } if(nums[left]+nums[right]<target){ left++; continue; } if(nums[left]+nums[right]>target){ right--; continue; } } return arrSum; }}解法3:哈希表
哈希表的解法就是把index和他所在的值放入map中,然后如果能够找到target减去当前索引值的差存在于哈希表中,那么就把这两个索引放入到新数组中返回。因为只需要遍历一遍数组,所以时间复杂度是O(n),空间复杂度也是O(n)
public class Solution { public int[] twoSum(int[] nums, int target) { int[] arrSum = new int[2]; if(nums==null||nums.length<2){ return arrSum; }
<span style="white-space:pre"></span>//我们把key设定为nums的值,value为索引,因为要判断target减去索引所在的值,key调用会方便一些 HashMap<Integer,Integer> ht = new HashMap<>(); for(int i=0;i<nums.length;i++){ if(!ht.containsKey(target-nums[i])){ ht.put(nums[i],i); }else{ arrSum[0]=ht.get(target-nums[i]); arrSum[1]=i; break; } } return arrSum; }}
0 0
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 【LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- leetcode 1. Two Sum
- [leetcode] 1. Two Sum
- leetcode 1. Two Sum
- Leetcode- 1. Two Sum
- LeetCode-1.Two Sum
- Leetcode 1. Two Sum
- vec
- HashCode 和 Equals 的使用 - 使用自定义对象作为HashMap的Key例子
- 项目管理之甘特图
- 這是我的java程序之路的開始
- poj 2356 poj3370
- [LeetCode]1. Two Sum
- 代码片段 notepad++
- 代码片段notepad++ 2
- 英文原文:MVC vs. MVP vs. MVVM
- php访问数据库出错:Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given i
- LeetCode 6: ZigZag Conversion
- PHP+MySQL分页显示示例分析
- 怎样卸载干净Oracle
- 瓦斯弹 是大人撒三等功第三个撒的豆腐干地方