【菜鸡学算法】两数之和

这篇博客讨论了在寻找数组中两个数之和等于目标值的问题上,两种不同的解决方案。第一种是暴力破解,通过双重循环遍历数组,时间复杂度为O(n^2)。第二种是使用哈希映射,将遍历过的数值存储在HashMap中,以O(n)的时间复杂度找到答案。这两种方法在时间和空间复杂度上有所不同,哈希映射提供了更优的效率。

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

暴力破解

import java.util.*;


public class Solution {
    /**
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
        // write code here
        int[] res = new int[2];
        int n = numbers.length;
        for(int i = 0;i < n-1;i++){
            for(int j = i+1;j < n;j++){
                if(numbers[i] + numbers[j] == target){
                    res[0] = i+1;
                    res[1] = j+1;
                    return res;
                }
            }
        }
            return res;
        }
};

时间复杂度O(n):时间复杂度为O(n方)
空间复杂度O(n):1

HashMap实现

import java.util.*;


public class Solution {
    /**
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
        // write code here
            Map<Integer, Integer> m = new HashMap<>();
            for(int i = 0;i < numbers.length;i++){
                if(m.get(target-numbers[i])!=null){
                    return new int[]{m.get(target-numbers[i])+1,i+1};
                }
                m.put(numbers[i],i);
            }
            return new int[]{0,0};
        }
}

时间复杂度O(n):时间复杂度为n
空间复杂度O(n):定义了一个HashMap用来存储遍历过的值,所以空间复杂度为n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值