LeetCode:两数之和
2019-02-22 11:08
99 查看
两数之和
题目叙述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:
方法一
1、先将数组的元素所有的值赋给另一个数组
2、将新数组进行排序
3、两个指针向中间连着跑,相遇跳出或者找到何为target的跳出
4、找出两个值在原数组的位置返回结果。
时间复杂度O(nlogn)
实现代码:
class Solution { public int[] twoSum(int[] nums, int target) { int [] a=new int[nums.length]; for(int i=0;i<nums.length;i++){ a[i]=nums[i]; } Arrays.sort(a); int i=0,j=a.length-1; while(i<j){ if(a[i]+a[j]==target){ break; } else if(a[i]+a[j]>target){ j--; } else{ i++; } } int x,y; for(x=0;x<nums.length&&nums[x]!=a[i];x++); for(y=0;y<nums.length&&(nums[y]!=a[j]||x==y);y++); return new int[]{x,y}; } }
方法二:
学Java的大家都知道一种集合类型也就是Map,Map是一个k-v的结构,这里就不详细解释了。
我们将每个元素的值和它的索引添加到表中。然后在添加的过程中,我们将检查每个元素所对应的目标元素(target - nums[i]target−nums[i])是否存在于表中。整体时间复杂度就是O(n)。
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } return new int[2]; } }
更多的内容在简书
相关文章推荐
- 1.leetcode 两数之和-Two Sum
- [leetcode]两数相加
- leetcode--两数相加
- leetcode--两数之和--python
- Leetcode 1. Two Sum 两数之和
- 【LeetCode】【数组】【简单】【两数之和】
- 刷LeetCode(1)——两数相加
- leetcode2:两数相加
- leetcode 两数相加
- Datawhale-LeetCode集训打卡-两数之和
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- 【LeetCode】1. 两数之和
- LeetCode-2 两数相加 Add Two Numbers
- [leetcode, python] Two Sum 两数之和等于某数
- 两数之和 - LeetCode
- 从零打卡leetcode之day 1--两数之和
- [LeetCode] Add Two Numbers 两数相加
- LeetCode 167. 两数之和 II - 输入有序数组 Python
- LeetCode - 1. 两数之和
- LeetCode 1. 两数之和