简单算法题之 Two Sum

这篇博客介绍了如何解决寻找数组中两个数相加等于特定目标值的问题。文章给出了具体例子,并讨论了两种方法:加法和减法策略,虽然两者的时间复杂度均为O(n^2)。博主选择了减法策略进行详细阐述。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

####Question:
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers(both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution.
####Example:

Input: numbers[]={2,7,11,15},
target = 9
Output: index1 =1, index2 = 2

其实,问题还是挺简单。意思就是说,给你一个数组 a 和一个数 c ,找出数组里面两个元素 a[i] 和 a[j] 加起来的和等于c。你需要返回这两个元素的下标,并且 i < j。

####思路:

  1. 加法:让数组里面两个数加起来去跟target比较是,时间复杂度是O(n^2),即 是两个for循环遍历数组a。
  2. 减法:用target依次减去数组的元素a[i],把差遍历后面的数组a[i+1]…a[n],判断数组里是否有元素等于这个差。其实也是两个for循环,时间复杂度也是O(n^2)。

####下面,我使用减法来做。

package TwoSum;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {

	public static void main(String[] args) {
		TwoSum t = new TwoSum();
		int [] numbers= {2,7,11,15};
		int target = 13;
		int [] res = t.twoSum(numbers, target);
		for(int i = 0; i < res.length; i++)
			System.out.print(i==res.length-1? res[i]:res[i]+",");
	}
	//返回两个下标
	public int[] twoSum(int[] numbers, int target){
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for(int i = 0; i < numbers.length; i++)
			map.put(numbers[i], i);
			
		for(int i = 0; i < numbers.length; i++){
			int newTarget = target - numbers[i];
			if(map.containsKey(newTarget)&&i < map.get(newTarget))
				return new int[]{i + 1, map.get(newTarget) + 1 };
		}
		return null;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值