LeetCode1--两数之和

一、问题描述:

给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你假设每种输入只会对应一个答案。但是数组中同一个元素不能使用两遍。
示例:

给定 nums=[2,7,11,15],target=9
因为nums[0]+nums[1]=2+7=9
所以返回[0,1]

二、传统的暴力查找:

   public int[] addnumber(int[] nums,int 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;
    }

三、优化的哈希表

public int[] addtwonumber(int[] nums, int target) {//一次遍历实现
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int value = target - nums[i];
            if (map.containsKey(value)) {//如果map中存在此插值,则返回
                res[0] = map.get(value);
                res[1] = i;
                return res;
            } else {//如果不存在,则存入map
                map.put(nums[i], i);
            }
        }
        return null;
    }

四、完整的代码测试

import javafx.css.converter.LadderConverter;

import java.util.HashMap;

public class test {
    public int[] addtwonumber(int[] nums, int target) {//一次遍历实现
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int value = target - nums[i];
            if (map.containsKey(value)) {//如果map中存在此插值,则返回
                res[0] = map.get(value);
                res[1] = i;
                return res;
            } else {//如果不存在,则存入map
                map.put(nums[i], i);
            }
        }
        return null;
    }
    public int[] addnumber(int[] nums,int 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;
    }

    public static void main(String[] args) {
        test a = new test();
        int[] nums = {2,7,11,15};
        int[] x = new int[2];
        int[] x1=new int[2];
        int index;
        x = a.addtwonumber(nums, 9);
        x1=a.addnumber(nums,9);
        System.out.println("哈希表查找的结果");
        if (x1 != null) {
            for (int temp :
                    x) {
                System.out.print(temp+" ");
            }
        }
        System.out.println("");
        System.out.println("传统的暴力查找结果:");
        if(x1!=null){
            for (int temp:
                 x1) {
                System.out.print(temp+" ");
            }
        }
    }
}

在这里插入图片描述

posted @   别团等shy哥发育  阅读(11)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示