目录
Leetcode | 1.两数之和
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
解题
暴力解法
最笨的方法:枚举出所有的情况,找出符合条件的两个数。
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] res = new int[2];
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){
if(nums[i]+nums[j] == target){
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
}
双指针(优化时间)
先排序,然后用双指针,左指针从左,用指针从最右开始依次寻找。优化了时间复杂度,只需遍历一层,无需双层遍历。因为要用额外的数组存储本来的数组方便存储本来的索引值,所以算是空间换时间。
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] res = new int[2];
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
Arrays.sort(nums);
int p = 0, q = n-1;
while(p<q){
if(nums[p]+nums[q] == target){
res[0] = list.indexOf(nums[p]);
res[1] = list.lastIndexOf(nums[q]);
return res;
}else if(nums[p]+nums[q] > target){
//当前总和大于target,右指针往左挪,使总和变小向target靠近
q