leetcode算法—两数之和 Two Sum

关注微信公众号:CodingTechWork,一起学习进步。
在这里插入图片描述

题目

Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

Example:

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

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

解题

1 暴力解题

class Solution {
    public int[] twoSum(int[] nums, int target) {
    	//遍历每个元素nums[i],查找是否存在值nums[j]相加后等于target。
        for (int i = 0; i < nums.length; i++){
            for(int j = i+1; j < nums.length;j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;  
    }
}

这种暴力解题,两层循环,每个元素遍历一遍,内部嵌套再把剩余的每个元素遍历一遍求和寻找目标合适元素,时间复杂度为o(n^2),空间复杂度为o(1)

2 2次遍历解题

class Solution {
    public int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap();
        //存储到HashMap中
        for (int i = 0; i < nums.length; i++){
            map.put(nums[i], i);
        }
        //遍历数组
        for (int i = 0; i < nums.length; i++) {
        	//算差值
            int result = target - nums[i];
            //在map中查找索引不是本身i的的差值即为结果值
            if(map.containsKey(result) && map.get(result) != i) {
                return new int[] {i,map.get(result)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
        
    }
}

这种两遍哈希表的方式,哈希表存储n个元素,增加了空间复杂度,第一次是遍历数组插入到哈希表中,时间复杂度为o(n),但是第二次查询时间由原来遍历数组的o(n)减少到o(1)。所以总体时间复杂度为o(n),空间复杂度为o(n)

3 一次遍历解题

class Solution {
    public int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            //计算结果
            int result = target - nums[i];
            //map中是否包含这个结果,若包含则返回该结果,及对应的目前数组的index
            if (map.containsKey(result)) {
                //map是后添加元素的,所以map索引在前,i在后
                return new int[]{map.get(result), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("no two sum solution");
        
    }
}

这种方式也是参考了题解中的第一个官方的,自己想不到;他是采用了一次遍历的同时,最后将前面遍历的值放入到map中,然后后续的遍历过程中,不断的把map的值(也就是数组中已遍历的前方值)和当前后方值做比较。所以返回的时候,map的索引在前,i在后。

参考 two sum

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值