【LeetCode】 第一题 两数之和twoSum

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

实例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

暴力解法 

第一次做这道题采用直接遍历的求解方法:

import java.util.Arrays;

public class Sum_01 {
	
	public int[] twoSum(int[] nums, int target) {
		int[] res = new int[2];
        for(int i = 0; i < nums.length; i++) {
        	for(int j = i +1; j < nums.length; j++) {
        		int sum = nums[i] + nums [j];
        		if(sum == target) {
        			res[0] = i;
        			res[1] = j;
        			break;
        		}
        	}
        }
        return res;
    }
	
	public static void main(String[] args) {
		int[] nums = new int[] {2, 7, 11, 15};
		Sum_01 sum = new Sum_01();
		int[] res1 = sum.twoSum(nums, 9);
		System.out.println(Arrays.toString(res1));
	}
}

哈希表 

考虑建立一个哈希表,将数组的内容作为哈希表的关键字,数组下标作为值。通过将数组从头后面进行遍历,然后计算每次需要的另一个加数,在哈希表中查找该关键字是否存在,如果存在就得到关键字对应的值,也就是下标。

import java.util.Arrays;
import java.util.HashMap;

/**
 * 
 * @author liwenlong
 * HashMap 
 */

public class Sum_02 {

	public int[] twoSum(int[] nums, int target) {
		//创建哈希表
		HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); 
		int[] res = new int[2];
		for(int i = 0; i< nums.length; i++) {
			//put(Key,Value)
			m.put(nums[i],i); //数组内容作为键,下标作为值
		}
		for(int j = 0; j < nums.length; j++) {
			//和减去当前位置的数组
			int t = target - nums[j];
			if(m.containsKey(t) && m.get(t) != j) { //如果包含键t,且下标不相同
				res[0] = j;
				res[1] = m.get(t); //存的值为下标
				break;
			}
		}
		return res;
	}
	
	public static void main(String[] args) {
		int[] nums = new int[] {2, 7, 11, 15};
		Sum_02 sum = new Sum_02();
		int[] res1 = sum.twoSum(nums, 9);
		System.out.println(Arrays.toString(res1));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程芝士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值