[LeetCode] 1. Two Sum

原题链接: https://leetcode.com/problems/two-sum/

1. 题目描述

Leetcode 第一题

输入:一组整数数组,和一个target值。
输出:两个整数加起来如果等于target,输出这两个整数的下标

每个输入都会有一个解,同一次输入不会有相同的整数。

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

2. 做题思路

2.1 暴力搜索

使用i、j两个下标,对数组进行遍历,当找到 nums[i] + nums[j] == target 的i、j时,返回。时间复杂度O(n^2)

class Solution {
    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++){
				if(nums[i]+nums[j] == target){
                    
                    res[0] = i;
                    res[1] = j;
					return res;
				}
			}
		}
		return res;
	}
}

2.2 借助HashMap,两次循环

什么是HashMap?

HashMap由数组和链表组成,基于哈希表的Map接口实现,是以key-value存储形式存在。
系统会根据hash算法来计算key-value的存储位置,可以通过key快速存取value
允许对象值为null,并且没有个数限制

HashMap怎么用?

public void hashex(){
		//创建HashMap
		HashMap<Integer, String> hexample = new HashMap<>();
		
		//输入值,使用put方法
		hexample.put(1, "aa");//1是key,aa是value
		hexample.put(2, "bb");
		hexample.put(3, "cc");
		hexample.put(4, "dd");
		hexample.put(5, "ee");
		
		//输出值,使用get方法
		System.out.println(hexample.get(1));//输出结果为aa
		
		//判断是否存在某个key或者value
		System.out.println(hexample.containsKey(1));//输出结果为true
		System.out.println(hexample.containsKey(6));//输出结果为false
		System.out.println(hexample.containsValue("aa"));//输出结果为true
		System.out.println(hexample.containsValue("va"));//输出结果为false
	}

第一遍循环,先把数组nums存到HashMap里面去。
第二遍循环,遍历数组,寻找匹配的值。
时间复杂度O(n)。

class Solution {
    public int[] twoSum(int[] nums, int target) {
		
        int[] res = new int[2];
  
		HashMap<Integer, Integer> nummap = new HashMap<>();
		for(int i = 0;i<nums.length;i++){
			nummap.put(nums[i], i);
		}
		for(int i = 0;i<=nums.length;i++)
		{
			int temp = target - nums[i];
			if(nummap.containsKey(temp) && nummap.get(temp) != i ) {
				res[0] = i;
				res[1] = nummap.get(temp);
				return res;
			}
		}
		return res;
	}
}

2.3 只用一次循环的HashMap

和上面的方法类似,但是,不需要把数组放入HashMap的第一遍循环了,直接遍历数组,如果在HashMap里面没有对应的temp的话,就放入一个值,否则就返回。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> nummap2 = new HashMap<>();
		int lengthnum = nums.length;
		int temp = 0;
		for(int i = 0;i<lengthnum ; i++) {
			temp = target - nums[i];
			if(nummap2.containsKey(temp)) {
				return new int[] {nummap2.get(temp),i} ;//注意这里的先后顺序,一定是nummap2.get(temp)在前,i在后
			}
			else {
				nummap2.put(nums[i], i);
			}
		}
		return new int[] {0,0};
    }
}

3. n-Sum专题相关题目

1. Two Sum
15. 3Sum
16. 3Sum Closest
18. 4Sum
167. Two Sum II - Input array is sorted
560. Subarray Sum Equals K
653. Two Sum IV - Input is a BST

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值